steid

@jamesgill /

steid/src/infrastructure/web/rate_limit.rs
Rust38.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, try_app_context},
22 router::{Body, HeaderMap, Response, StatusCode, header::RETRY_AFTER, headers},
23};
24
25use crate::application::AppConfig;
26use crate::infrastructure::metrics::{Limiter, metrics};
27
28/// How long a window lasts.
29const WINDOW: Duration = Duration::from_secs(60);
30
31/// Attempts one client may make per window.
32///
33/// Ten a minute is far above what a person signing in ever needs — a mistyped
34/// password twice, then a password manager — and far below what makes guessing
35/// worthwhile: an online attack against even a weak six-character password would take
36/// centuries at this rate.
37const PER_CLIENT: u32 = 10;
38
39/// Attempts *everyone together* may make per window.
40///
41/// This is the backstop for a forged client key (see [`client_key`]). Without a peer
42/// address there is no way to prove a caller is who its headers claim, so an attacker
43/// who can forge a different `X-Forwarded-For` per request would otherwise get an
44/// unlimited number of per-client budgets. Sixty a minute is six independent people
45/// each hitting their own limit at once, which a single-owner instance will never see,
46/// and it turns key forgery from a bypass into a six-fold speed-up.
47///
48/// The cost is that a flood can lock out a legitimate sign-in for up to a minute.
49/// That is the right way round: a temporary denial of the login form is recoverable,
50/// a guessed password is not.
51const GLOBAL: u32 = 60;
52
53/// Distinct client keys tracked at once.
54///
55/// The map is keyed by something the caller influences, so it must not be allowed to
56/// grow with the number of keys an attacker can invent. Past this many live keys,
57/// expired entries are swept and any still-unknown key falls back to the global
58/// window alone — which is stricter, not laxer, so filling the map is not a way out.
59const MAX_KEYS: usize = 4096;
60
61/// Token authentications one client may make per window, on the git transport.
62///
63/// Far above [`PER_CLIENT`] because git is chatty and a person is not: one `git clone`
64/// authenticates two or three times, a `git push` twice, and a script fetching a
65/// handful of remotes in a loop makes a burst of them. Sixty a minute is roughly twenty
66/// clones a minute from one address — beyond anything a person or a CI job does — while
67/// still bounding the work an anonymous caller can force the server to do. That work is
68/// a SHA-256 and one indexed lookup, not an Argon2 hash, so this is a cap on volume
69/// rather than a defence against guessing: a token is 256 bits and cannot be guessed at
70/// any rate.
71const GIT_PER_CLIENT: u32 = 60;
72
73/// Git-transport authentications *everyone together* may make per window.
74///
75/// Ten independent clients each at their own limit, for the same reason [`GLOBAL`]
76/// exists: without a peer address a client key can be forged, and this is what keeps
77/// forging one from being an unlimited bypass.
78const GIT_GLOBAL: u32 = 600;
79
80/// The limiter guarding token authentication on the git transport.
81///
82/// A separate budget rather than a share of the sign-in one, because the two have
83/// nothing to do with each other: a clone would spend a person's login allowance in
84/// three requests, and a flood of clones must not be able to lock someone out of
85/// `/auth/login`. Same window, same client key, different numbers.
86#[derive(Debug)]
87pub struct GitAuthLimiter(RateLimiter);
88
89impl Default for GitAuthLimiter {
90 fn default() -> Self {
91 Self(RateLimiter::new(
92 WINDOW,
93 GIT_PER_CLIENT,
94 GIT_GLOBAL,
95 MAX_KEYS,
96 ))
97 }
98}
99
100/// Records a git-transport authentication attempt, and says how long to wait if the
101/// caller has spent its budget.
102///
103/// Returns the retry-after rather than a response, because the git routes answer with
104/// their own streaming body type and cannot use the one [`throttled`] builds.
105pub fn git_auth_throttled(cx: &Cx) -> Option<Duration> {
106 match app_context::<GitAuthLimiter>(cx).0.check(&client_key(cx)) {
107 Decision::Allowed => None,
108 Decision::Throttled(retry_after) => {
109 eprintln!("steid: rate limited a git authentication attempt");
110 metrics().record_rate_limited(Limiter::GitAuth);
111 Some(retry_after)
112 }
113 }
114}
115
116/// Archive downloads per client per minute.
117///
118/// An archive is a whole pack of the repository per request, on an anonymous endpoint
119/// that every tag row and the landing page now link to — the most expensive thing a
120/// stranger can ask for, and the first thing a crawler follows. Ten a minute is far
121/// above a person clicking and far below a bot walking the tags page.
122const ARCHIVE_PER_CLIENT: u32 = 10;
123
124/// Archive downloads across every client per minute. Bounds the total pack work the
125/// process will do for anonymous downloads, however many addresses ask.
126const ARCHIVE_GLOBAL: u32 = 60;
127
128/// The limiter for archive downloads. Its own budget, for the reason
129/// [`GitAuthLimiter`] has one: a download must not spend a sign-in allowance, and a
130/// flood of downloads must not lock anyone out of the login form.
131#[derive(Debug)]
132pub struct ArchiveLimiter(RateLimiter);
133
134impl Default for ArchiveLimiter {
135 fn default() -> Self {
136 Self(RateLimiter::new(
137 WINDOW,
138 ARCHIVE_PER_CLIENT,
139 ARCHIVE_GLOBAL,
140 MAX_KEYS,
141 ))
142 }
143}
144
145/// Records an archive download, and says how long to wait if the caller has spent
146/// its budget. Returns a duration rather than a response for the same reason
147/// [`git_auth_throttled`] does: the archive route streams its own body type.
148pub fn archive_throttled(cx: &Cx) -> Option<Duration> {
149 match app_context::<ArchiveLimiter>(cx).0.check(&client_key(cx)) {
150 Decision::Allowed => None,
151 Decision::Throttled(retry_after) => {
152 eprintln!("steid: rate limited an archive download");
153 metrics().record_rate_limited(Limiter::Archive);
154 Some(retry_after)
155 }
156 }
157}
158
159/// Code searches per client per minute.
160///
161/// A search is one `git grep` across a whole revision: a subprocess that may run for up
162/// to the 20-second read timeout and write up to 4 MiB before the reader cuts it off.
163/// The byte cap bounds the memory; nothing bounded the *CPU*, and this is the most
164/// expensive unauthenticated read after an archive.
165///
166/// Twenty a minute, because a person searching types a query, reads the results,
167/// narrows it and types again — a handful a minute, and twenty is far above the
168/// fastest anyone does that. It is deliberately looser than the archive's ten, since a
169/// grep of a warm repository is milliseconds where a pack is seconds, and deliberately
170/// tighter than an ordinary page, which spawns no open-ended process at all.
171///
172/// **An empty query does not count.** `/search` with nothing on it renders the form and
173/// never reaches grep, so it costs no more than any other repository page; charging for
174/// it would mean a visitor could lock themselves out of searching by opening the search
175/// box. The limiter is checked once a query is in hand and before any `git` is spawned.
176const SEARCH_PER_CLIENT: u32 = 20;
177
178/// Code searches across every client per minute. Six addresses at their full budget,
179/// the ratio [`ARCHIVE_GLOBAL`] uses, so a handful of crawlers cannot between them keep
180/// a grep running permanently.
181const SEARCH_GLOBAL: u32 = 120;
182
183/// The limiter for the code search page. Its own budget, for the reason
184/// [`ArchiveLimiter`] has one: a search must not spend a sign-in allowance, and a
185/// crawler walking `?q=` must not lock anyone out of the login form.
186#[derive(Debug)]
187pub struct SearchLimiter(RateLimiter);
188
189impl Default for SearchLimiter {
190 fn default() -> Self {
191 Self(RateLimiter::new(
192 WINDOW,
193 SEARCH_PER_CLIENT,
194 SEARCH_GLOBAL,
195 MAX_KEYS,
196 ))
197 }
198}
199
200/// Records a code search, and says how long to wait if the caller has spent its budget.
201///
202/// A duration rather than a response, like [`archive_throttled`]: the search page
203/// renders its refusal as one of its own states, so it needs the number of seconds and
204/// not somebody else's body.
205pub fn search_throttled(cx: &Cx) -> Option<Duration> {
206 match app_context::<SearchLimiter>(cx).0.check(&client_key(cx)) {
207 Decision::Allowed => None,
208 Decision::Throttled(retry_after) => {
209 eprintln!("steid: rate limited a code search");
210 metrics().record_rate_limited(Limiter::Search);
211 Some(retry_after)
212 }
213 }
214}
215
216/// Unauthenticated `/api/instance` polls per client per minute.
217///
218/// One a second, which is as fast as a provisioner sensibly polls a machine it has just
219/// booted, and the poll is the whole reason the unauthenticated form exists: something
220/// has to know when to hand an owner their claim link. The work per call is one `select
221/// exists` against a local file, so this is a cap on noise and on how cheaply a stranger
222/// can watch an instance's claimed state flip, not a defence against guessing — there is
223/// no secret here to guess.
224const INSTANCE_PER_CLIENT: u32 = 60;
225
226/// Unauthenticated `/api/instance` polls across every client per minute. Ten provisioners
227/// each at their own limit, for the reason [`GLOBAL`] exists.
228const INSTANCE_GLOBAL: u32 = 600;
229
230/// The limiter for the unauthenticated `/api/instance`. Its own budget, so a polling
231/// provisioner cannot spend anybody's sign-in allowance and a flood of polls cannot lock
232/// the owner out of the login form.
233///
234/// Only the unauthenticated form is counted: a caller holding the operator token has
235/// already proved it is the control plane, and rate-limiting the machine that manages the
236/// machine buys nothing.
237#[derive(Debug)]
238pub struct InstanceLimiter(RateLimiter);
239
240impl Default for InstanceLimiter {
241 fn default() -> Self {
242 Self(RateLimiter::new(
243 WINDOW,
244 INSTANCE_PER_CLIENT,
245 INSTANCE_GLOBAL,
246 MAX_KEYS,
247 ))
248 }
249}
250
251/// Records an unauthenticated instance poll, returning the 429 to send when the caller
252/// has spent its budget.
253pub fn instance_throttled(cx: &Cx) -> Option<Response> {
254 match app_context::<InstanceLimiter>(cx).0.check(&client_key(cx)) {
255 Decision::Allowed => None,
256 Decision::Throttled(retry_after) => {
257 eprintln!("steid: rate limited an instance poll");
258 Some(too_many_requests(retry_after))
259 }
260 }
261}
262
263/// Unauthorized `/metrics` attempts one client may make per window.
264///
265/// Thirty a minute, and **only a request that failed the operator check ever counts**:
266/// an authorized scrape spends nothing, so a flood from somewhere else can never starve
267/// the thing that is actually collecting. That is the whole reason the limiter is applied
268/// after the bearer comparison rather than before it, which is the opposite of the order
269/// `/auth/login` uses — there, the expensive work is the hashing and it has to be gated
270/// before it runs; here the check is one constant-time byte comparison and gating it
271/// early would buy nothing while handing an attacker a way to blind an operator.
272///
273/// The number is what bounds online guessing of the operator token. That token is
274/// operator-chosen and may be weak, so the cap matters; thirty a minute makes even a
275/// short token take years, and no legitimate caller ever reaches it because a legitimate
276/// caller is authorized and is not counted.
277const METRICS_PER_CLIENT: u32 = 30;
278
279/// Unauthorized `/metrics` attempts across every client per window. Ten independent
280/// clients at their own limit, for the reason [`GLOBAL`] exists: a client key can be
281/// forged without a peer address, and this is what keeps forging one from being an
282/// unlimited bypass.
283const METRICS_GLOBAL: u32 = 300;
284
285/// The limiter guarding the operator token on `/metrics`.
286///
287/// Its own budget, like [`GitAuthLimiter`] and [`ArchiveLimiter`]: guessing an operator
288/// token must not spend a person's sign-in allowance, and a flood at `/metrics` must not
289/// lock anybody out of the login form.
290#[derive(Debug)]
291pub struct MetricsLimiter(RateLimiter);
292
293impl Default for MetricsLimiter {
294 fn default() -> Self {
295 Self(RateLimiter::new(
296 WINDOW,
297 METRICS_PER_CLIENT,
298 METRICS_GLOBAL,
299 MAX_KEYS,
300 ))
301 }
302}
303
304/// Records an unauthorized `/metrics` attempt, returning the 429 to send when the caller
305/// has spent its budget.
306///
307/// Call it **only** on the unauthorized path — see [`METRICS_PER_CLIENT`].
308pub fn metrics_throttled(cx: &Cx) -> Option<Response> {
309 match app_context::<MetricsLimiter>(cx).0.check(&client_key(cx)) {
310 Decision::Allowed => None,
311 Decision::Throttled(retry_after) => {
312 // No token, no address, nothing but the fact. The presented token is never
313 // logged, exactly as a password is not.
314 eprintln!("steid: rate limited an unauthorized /metrics request");
315 metrics().record_rate_limited(Limiter::Metrics);
316 Some(too_many_requests(retry_after))
317 }
318 }
319}
320
321/// How long a backup window lasts. An hour, not a minute — see [`BACKUP_PER_CLIENT`].
322const BACKUP_WINDOW: Duration = Duration::from_secs(3_600);
323
324/// Instance backups one client may download per hour.
325///
326/// **The most expensive request Steid serves.** One of these is a `VACUUM INTO` of the
327/// whole database plus a gzip of every byte of every repository, written to disk and
328/// then streamed — and unlike an archive download it cannot be answered from a cache or
329/// short-circuited by an `ETag`, because every backup is a new one.
330///
331/// Two an hour is more than anybody takes by hand: a person clicks it, notices the
332/// download, and goes away. It is a cap on a stuck script and a double-clicked button
333/// rather than a defence against a stranger — the route is owner-only, so a stranger
334/// never reaches the work at all. The window is an hour rather than a minute because
335/// "two a minute" would be twenty an hour, which is twenty full copies of the instance.
336const BACKUP_PER_CLIENT: u32 = 2;
337
338/// Instance backups across every client per hour.
339///
340/// Four owners' worth. An instance has one owner, so this is purely the backstop against
341/// a forged client key that [`GLOBAL`] exists for — it bounds the process to eight full
342/// copies of itself an hour however many addresses ask.
343const BACKUP_GLOBAL: u32 = 8;
344
345/// The limiter for instance backup downloads. Its own budget and its own window, for the
346/// reason [`ArchiveLimiter`] has one, twice over: a backup must not spend a sign-in
347/// allowance, and it is expensive on a scale nothing else on the site is.
348#[derive(Debug)]
349pub struct BackupLimiter(RateLimiter);
350
351impl Default for BackupLimiter {
352 fn default() -> Self {
353 Self(RateLimiter::new(
354 BACKUP_WINDOW,
355 BACKUP_PER_CLIENT,
356 BACKUP_GLOBAL,
357 MAX_KEYS,
358 ))
359 }
360}
361
362/// Records a backup download, and says how long to wait if the caller has spent its
363/// budget. A duration rather than a response, like [`archive_throttled`]: the route
364/// streams a file and uses its own body type.
365pub fn backup_throttled(cx: &Cx) -> Option<Duration> {
366 match app_context::<BackupLimiter>(cx).0.check(&client_key(cx)) {
367 Decision::Allowed => None,
368 Decision::Throttled(retry_after) => {
369 eprintln!("steid: rate limited a backup download");
370 Some(retry_after)
371 }
372 }
373}
374
375/// Reset-link requests per client per minute.
376///
377/// Its own budget rather than a share of the sign-in one, and the reason is not
378/// symmetry: `/auth/reset/{token}` is a **page**, and a person opens it, reloads it, and
379/// mistypes the confirmation once or twice. Counted against [`PER_CLIENT`], six page
380/// loads spent most of a sign-in allowance and the seventh answered 429 — found by
381/// taking screenshots, which is exactly what a person clicking around looks like. Worse
382/// in the other direction: a reader reloading a link they were mailed must not be able
383/// to lock themselves out of `/auth/login`.
384///
385/// Thirty a minute is far above anyone reading a mail and far below anything worth
386/// doing to a 256-bit token, which cannot be guessed at any rate. What it actually
387/// bounds is the Argon2 the POST runs — thirty hashes a minute from one address.
388const RESET_PER_CLIENT: u32 = 30;
389
390/// Reset-link requests across every client per minute. Bounds the hashing the process
391/// will do for anonymous resets, however many addresses ask.
392const RESET_GLOBAL: u32 = 120;
393
394/// The limiter for `/auth/reset/{token}`, both the form and the submission.
395#[derive(Debug)]
396pub struct ResetLimiter(RateLimiter);
397
398impl Default for ResetLimiter {
399 fn default() -> Self {
400 Self(RateLimiter::new(
401 WINDOW,
402 RESET_PER_CLIENT,
403 RESET_GLOBAL,
404 MAX_KEYS,
405 ))
406 }
407}
408
409/// Records a reset-link request, returning the 429 to send when the caller has spent its
410/// budget. Same shape as [`throttled`], different numbers.
411pub fn reset_throttled(cx: &Cx) -> Option<Response> {
412 match app_context::<ResetLimiter>(cx).0.check(&client_key(cx)) {
413 Decision::Allowed => None,
414 Decision::Throttled(retry_after) => {
415 eprintln!("steid: rate limited a password reset attempt");
416 Some(too_many_requests(retry_after))
417 }
418 }
419}
420
421/// The shared limiter. One per process, held in Topcoat's app context.
422#[derive(Debug)]
423pub struct RateLimiter {
424 window: Duration,
425 per_client: u32,
426 global: u32,
427 max_keys: usize,
428 state: Mutex<State>,
429}
430
431#[derive(Debug)]
432struct State {
433 clients: HashMap<Box<str>, Window>,
434 global: Window,
435}
436
437/// A fixed window: when it opened, and how many attempts have landed in it.
438#[derive(Debug, Clone, Copy)]
439struct Window {
440 opened: Instant,
441 hits: u32,
442}
443
444impl Window {
445 fn new(now: Instant) -> Self {
446 Self {
447 opened: now,
448 hits: 0,
449 }
450 }
451
452 /// Records an attempt, rolling into a fresh window first if this one has expired.
453 fn record(&mut self, now: Instant, window: Duration) -> u32 {
454 if now.duration_since(self.opened) >= window {
455 *self = Self::new(now);
456 }
457
458 self.hits = self.hits.saturating_add(1);
459 self.hits
460 }
461
462 fn expired(&self, now: Instant, window: Duration) -> bool {
463 now.duration_since(self.opened) >= window
464 }
465
466 fn remaining(&self, now: Instant, window: Duration) -> Duration {
467 window.saturating_sub(now.duration_since(self.opened))
468 }
469}
470
471/// What the limiter decided about one attempt.
472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
473pub enum Decision {
474 Allowed,
475 /// Refused, with how long until the window it exhausted rolls over.
476 Throttled(Duration),
477}
478
479impl Default for RateLimiter {
480 fn default() -> Self {
481 Self::new(WINDOW, PER_CLIENT, GLOBAL, MAX_KEYS)
482 }
483}
484
485impl RateLimiter {
486 /// Builds a limiter with explicit limits. Tests use this; `main` uses
487 /// [`Default`].
488 #[must_use]
489 pub fn new(window: Duration, per_client: u32, global: u32, max_keys: usize) -> Self {
490 Self {
491 window,
492 per_client,
493 global,
494 max_keys,
495 state: Mutex::new(State {
496 clients: HashMap::new(),
497 global: Window::new(Instant::now()),
498 }),
499 }
500 }
501
502 /// Records an attempt for `key` and says whether it may proceed.
503 pub fn check(&self, key: &str) -> Decision {
504 self.check_at(key, Instant::now())
505 }
506
507 /// [`check`](Self::check) with the clock supplied, so tests can move time.
508 fn check_at(&self, key: &str, now: Instant) -> Decision {
509 let mut state = self.state.lock().unwrap_or_else(|poisoned| {
510 // A panic while holding the lock would otherwise disable the limiter for
511 // the life of the process, which is the wrong way to fail.
512 self.state.clear_poison();
513 poisoned.into_inner()
514 });
515
516 // Every attempt counts against the global window, including one that is about
517 // to be refused for its own key: an attacker rotating keys still pays here.
518 let global_hits = state.global.record(now, self.window);
519 if global_hits > self.global {
520 return Decision::Throttled(state.global.remaining(now, self.window));
521 }
522
523 if !state.clients.contains_key(key) && state.clients.len() >= self.max_keys {
524 let window = self.window;
525 state.clients.retain(|_, entry| !entry.expired(now, window));
526
527 if state.clients.len() >= self.max_keys {
528 // Still full of live entries, so this attempt is covered by the
529 // global window only. Refusing to grow is what bounds the memory.
530 return Decision::Allowed;
531 }
532 }
533
534 let entry = state
535 .clients
536 .entry(key.into())
537 .or_insert_with(|| Window::new(now));
538
539 if entry.record(now, self.window) > self.per_client {
540 return Decision::Throttled(entry.remaining(now, self.window));
541 }
542
543 Decision::Allowed
544 }
545
546 /// How many client keys are currently held. For tests and diagnostics.
547 #[must_use]
548 pub fn tracked_keys(&self) -> usize {
549 self.state.lock().map_or(0, |state| state.clients.len())
550 }
551}
552
553/// Applies the shared limiter to this request, returning the 429 to send when the
554/// caller has spent its budget.
555///
556/// Call it first in a handler, before any password hashing or token comparison.
557pub fn throttled(cx: &Cx) -> Option<Response> {
558 match app_context::<RateLimiter>(cx).check(&client_key(cx)) {
559 Decision::Allowed => None,
560 Decision::Throttled(retry_after) => {
561 eprintln!("steid: rate limited an auth attempt");
562 metrics().record_rate_limited(Limiter::Auth);
563 Some(too_many_requests(retry_after))
564 }
565 }
566}
567
568/// The 429 itself. Deliberately a bare line of text: it says nothing about which
569/// limit was hit or what the instance is.
570fn too_many_requests(retry_after: Duration) -> Response {
571 let seconds = retry_after.as_secs().max(1);
572
573 let mut response = Response::new(Body::from("too many attempts, try again shortly\n"));
574 *response.status_mut() = StatusCode::TOO_MANY_REQUESTS;
575 response.headers_mut().insert(RETRY_AFTER, seconds.into());
576
577 response
578}
579
580/// What the limiter counts against — an approximation of the client's address.
581///
582/// **Topcoat 0.5 does not expose the peer address.** `internal_serve` discards it at
583/// accept time (`let (stream, _remote) = accepted?;`) and never puts it on the request
584/// extensions, so a handler has nothing but headers to go on. That constrains this
585/// entirely, and it is worth restating rather than rediscovering.
586///
587/// So: the **rightmost** `X-Forwarded-For` entry, then `X-Real-IP`, then a single
588/// shared key.
589///
590/// Rightmost, not leftmost, because a proxy *appends* the address it accepted the
591/// connection from. A client that sends its own `X-Forwarded-For: 1.2.3.4` gets
592/// `1.2.3.4, <real address>` by the time Steid sees it, so the last entry is the one
593/// the nearest proxy wrote and the only one it cannot forge. The leftmost entry —
594/// what "the real client IP" usually means — is exactly the attacker-controlled one.
595/// This assumes a single proxy hop; behind two, the rightmost entry is the inner
596/// proxy, and every client collapses onto one key. Stricter, so safe to be wrong
597/// about.
598///
599/// That trade-off is what `STEID_TRUSTED_PROXY` closes. Off — the default, and what a
600/// directly exposed instance must stay on — no header is read at all and every caller
601/// shares [`SHARED_KEY`], so a forged `X-Forwarded-For` buys nothing and only the global
602/// caps apply. On, the headers are read as described above, which is correct exactly when
603/// something in front is appending them. The cost of leaving it off is that one flood
604/// exhausts the shared window for everybody, which is a recoverable denial of the login
605/// form rather than an unlimited guessing budget — the right way round.
606fn client_key(cx: &Cx) -> String {
607 // `try_app_context` rather than `app_context`: a context built without a config —
608 // no context Steid builds, but a test could — falls to the stricter behaviour
609 // rather than panicking or trusting headers by accident.
610 let trusted = try_app_context::<AppConfig>(cx).is_some_and(|config| config.trusted_proxy);
611
612 key_from(trusted, headers(cx))
613}
614
615/// [`client_key`] without the request, so the rule can be tested: **Topcoat 0.5 gives no
616/// way to build a `Cx`**, and the header-reading half is the half worth pinning.
617fn key_from(trusted_proxy: bool, headers: &HeaderMap) -> String {
618 if !trusted_proxy {
619 return SHARED_KEY.to_owned();
620 }
621
622 let value = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
623
624 let forwarded = value("x-forwarded-for")
625 .and_then(|list| list.rsplit(',').next())
626 .and_then(address);
627
628 forwarded
629 .or_else(|| value("x-real-ip").and_then(address))
630 // No proxy header at all: everyone shares one window. Right for a directly
631 // exposed instance, where the alternative is no limit; a proxy that forwards
632 // neither header collapses its whole userbase into this key.
633 .unwrap_or_else(|| SHARED_KEY.to_owned())
634}
635
636/// The key every caller shares when there is nothing trustworthy to tell them apart.
637const SHARED_KEY: &str = "direct";
638
639/// Accepts a header fragment only if it looks like an address, so a hostile header
640/// cannot become an arbitrarily large or arbitrarily weird map key.
641fn address(raw: &str) -> Option<String> {
642 /// Longest textual IPv6 address, with a zone and an embedded IPv4 tail.
643 const MAX: usize = 64;
644
645 let candidate = raw.trim();
646
647 let plausible = !candidate.is_empty()
648 && candidate.len() <= MAX
649 && candidate
650 .chars()
651 .all(|c| c.is_ascii_hexdigit() || matches!(c, '.' | ':' | '%' | '[' | ']'));
652
653 plausible.then(|| candidate.to_owned())
654}
655
656#[cfg(test)]
657mod tests {
658 use super::*;
659
660 fn limiter() -> RateLimiter {
661 RateLimiter::new(Duration::from_secs(60), 3, 100, 16)
662 }
663
664 #[test]
665 fn allows_attempts_up_to_the_limit() {
666 let limiter = limiter();
667 let now = Instant::now();
668
669 for _ in 0..3 {
670 assert_eq!(limiter.check_at("a", now), Decision::Allowed);
671 }
672 }
673
674 #[test]
675 fn refuses_the_attempt_after_the_limit() {
676 let limiter = limiter();
677 let now = Instant::now();
678
679 for _ in 0..3 {
680 limiter.check_at("a", now);
681 }
682
683 assert!(matches!(limiter.check_at("a", now), Decision::Throttled(_)));
684 }
685
686 #[test]
687 fn reports_how_long_until_the_window_rolls() {
688 let limiter = limiter();
689 let now = Instant::now();
690
691 for _ in 0..4 {
692 limiter.check_at("a", now);
693 }
694
695 let Decision::Throttled(retry_after) = limiter.check_at("a", now + Duration::from_secs(20))
696 else {
697 panic!("the key is over its limit");
698 };
699
700 assert_eq!(retry_after, Duration::from_secs(40));
701 }
702
703 #[test]
704 fn recovers_once_the_window_has_passed() {
705 let limiter = limiter();
706 let now = Instant::now();
707
708 for _ in 0..4 {
709 limiter.check_at("a", now);
710 }
711
712 assert_eq!(
713 limiter.check_at("a", now + Duration::from_secs(60)),
714 Decision::Allowed
715 );
716 }
717
718 #[test]
719 fn keys_are_independent() {
720 let limiter = limiter();
721 let now = Instant::now();
722
723 for _ in 0..4 {
724 limiter.check_at("a", now);
725 }
726
727 assert_eq!(limiter.check_at("b", now), Decision::Allowed);
728 }
729
730 #[test]
731 fn the_global_window_catches_a_caller_rotating_keys() {
732 let limiter = RateLimiter::new(Duration::from_secs(60), 3, 5, 16);
733 let now = Instant::now();
734
735 for index in 0..5 {
736 assert_eq!(
737 limiter.check_at(&format!("k{index}"), now),
738 Decision::Allowed
739 );
740 }
741
742 assert!(matches!(
743 limiter.check_at("k5", now),
744 Decision::Throttled(_)
745 ));
746 }
747
748 #[test]
749 fn the_map_does_not_grow_past_its_cap() {
750 let limiter = RateLimiter::new(Duration::from_secs(60), 3, u32::MAX, 16);
751 let now = Instant::now();
752
753 for index in 0..5_000 {
754 limiter.check_at(&format!("k{index}"), now);
755 }
756
757 assert!(limiter.tracked_keys() <= 16);
758 }
759
760 #[test]
761 fn expired_entries_are_swept_to_make_room() {
762 let limiter = RateLimiter::new(Duration::from_secs(60), 3, u32::MAX, 16);
763 let now = Instant::now();
764
765 for index in 0..16 {
766 limiter.check_at(&format!("old{index}"), now);
767 }
768
769 // A minute later every one of those has expired, so the newcomer is tracked
770 // rather than being waved through on the global window alone.
771 let later = now + Duration::from_secs(61);
772 for _ in 0..4 {
773 limiter.check_at("new", later);
774 }
775
776 assert!(matches!(
777 limiter.check_at("new", later),
778 Decision::Throttled(_)
779 ));
780 assert!(limiter.tracked_keys() <= 16);
781 }
782
783 #[test]
784 fn a_key_beyond_the_cap_is_still_covered_by_the_global_window() {
785 let limiter = RateLimiter::new(Duration::from_secs(60), 3, 20, 2);
786 let now = Instant::now();
787
788 for index in 0..20 {
789 limiter.check_at(&format!("k{index}"), now);
790 }
791
792 assert!(matches!(
793 limiter.check_at("k20", now),
794 Decision::Throttled(_)
795 ));
796 }
797
798 /// A header map built from pairs, since a `Cx` cannot be.
799 fn forwarded(pairs: &[(&str, &str)]) -> HeaderMap {
800 let mut headers = HeaderMap::new();
801 for (name, value) in pairs {
802 headers.insert(
803 topcoat::router::HeaderName::from_bytes(name.as_bytes()).expect("valid name"),
804 value.parse().expect("valid value"),
805 );
806 }
807 headers
808 }
809
810 #[test]
811 fn an_untrusted_proxy_keys_everyone_together() {
812 // The whole point of the default: a caller inventing a header per request must
813 // not buy itself a fresh per-client budget each time.
814 assert_eq!(
815 key_from(false, &forwarded(&[("x-forwarded-for", "203.0.113.7")])),
816 SHARED_KEY
817 );
818 assert_eq!(
819 key_from(false, &forwarded(&[("x-forwarded-for", "198.51.100.9")])),
820 SHARED_KEY
821 );
822 assert_eq!(
823 key_from(false, &forwarded(&[("x-real-ip", "203.0.113.7")])),
824 SHARED_KEY
825 );
826 }
827
828 #[test]
829 fn a_trusted_proxy_keys_on_the_rightmost_forwarded_entry() {
830 // The leftmost entry is the one the client wrote; the rightmost is the one the
831 // proxy appended and the only one it cannot forge.
832 assert_eq!(
833 key_from(
834 true,
835 &forwarded(&[("x-forwarded-for", "1.2.3.4, 203.0.113.7")])
836 ),
837 "203.0.113.7"
838 );
839 assert_eq!(
840 key_from(true, &forwarded(&[("x-real-ip", "203.0.113.7")])),
841 "203.0.113.7"
842 );
843 assert_eq!(key_from(true, &forwarded(&[])), SHARED_KEY);
844 }
845
846 #[test]
847 fn a_trusted_proxy_that_forwards_rubbish_falls_back_to_the_shared_key() {
848 assert_eq!(
849 key_from(true, &forwarded(&[("x-forwarded-for", "not an address")])),
850 SHARED_KEY
851 );
852 }
853
854 #[test]
855 fn an_address_is_accepted() {
856 assert_eq!(address(" 203.0.113.7 "), Some("203.0.113.7".to_owned()));
857 assert_eq!(address("2001:db8::1"), Some("2001:db8::1".to_owned()));
858 }
859
860 #[test]
861 fn a_hostile_header_value_is_rejected() {
862 assert_eq!(address(""), None);
863 assert_eq!(address("not an address"), None);
864 assert_eq!(address(&"9".repeat(65)), None);
865 }
866
867 #[test]
868 fn the_archive_limiter_allows_ten_downloads_a_minute_then_refuses() {
869 let limiter = ArchiveLimiter::default();
870 for _ in 0..ARCHIVE_PER_CLIENT {
871 assert!(matches!(limiter.0.check("a"), Decision::Allowed));
872 }
873 assert!(matches!(limiter.0.check("a"), Decision::Throttled(_)));
874 // Another client still has its own budget.
875 assert!(matches!(limiter.0.check("b"), Decision::Allowed));
876 }
877
878 #[test]
879 fn the_instance_poll_gets_a_budget_a_provisioner_can_live_inside() {
880 // A provisioner polls about once a second while a machine boots. This is the
881 // check that the budget has not been quietly collapsed into the sign-in one,
882 // which would throttle it after ten seconds.
883 const { assert!(INSTANCE_PER_CLIENT >= 60) };
884
885 let limiter = InstanceLimiter::default();
886 let now = Instant::now();
887
888 for _ in 0..INSTANCE_PER_CLIENT {
889 assert_eq!(limiter.0.check_at("a", now), Decision::Allowed);
890 }
891
892 assert!(matches!(
893 limiter.0.check_at("a", now),
894 Decision::Throttled(_)
895 ));
896 }
897
898 #[test]
899 fn the_metrics_limiter_bounds_token_guessing_without_touching_the_sign_in_budget() {
900 const { assert!(METRICS_PER_CLIENT > PER_CLIENT) };
901
902 let limiter = MetricsLimiter::default();
903 let now = Instant::now();
904
905 for _ in 0..METRICS_PER_CLIENT {
906 assert_eq!(limiter.0.check_at("a", now), Decision::Allowed);
907 }
908
909 assert!(matches!(
910 limiter.0.check_at("a", now),
911 Decision::Throttled(_)
912 ));
913 assert_eq!(
914 limiter.0.check_at("b", now),
915 Decision::Allowed,
916 "another client has its own budget"
917 );
918 }
919
920 #[test]
921 fn the_backup_limiter_allows_two_an_hour_then_refuses() {
922 let limiter = BackupLimiter::default();
923 let now = Instant::now();
924
925 for _ in 0..BACKUP_PER_CLIENT {
926 assert_eq!(limiter.0.check_at("a", now), Decision::Allowed);
927 }
928 assert!(matches!(
929 limiter.0.check_at("a", now),
930 Decision::Throttled(_)
931 ));
932
933 // Still refused most of an hour later: the window is an hour, not a minute, and
934 // this is the check that it has not silently become the shared one.
935 assert!(matches!(
936 limiter.0.check_at("a", now + Duration::from_secs(3_500)),
937 Decision::Throttled(_)
938 ));
939 assert_eq!(
940 limiter.0.check_at("a", now + Duration::from_secs(3_600)),
941 Decision::Allowed
942 );
943 }
944
945 #[test]
946 fn the_git_transport_gets_a_budget_a_clone_can_live_inside() {
947 // A `git clone` authenticates two or three times, so the sign-in limit of ten a
948 // minute would throttle the fourth clone in a minute. This is the check that the
949 // two budgets have not been quietly collapsed into one.
950 const { assert!(GIT_PER_CLIENT > PER_CLIENT * 4) };
951
952 let limiter = GitAuthLimiter::default();
953 let now = Instant::now();
954
955 for _ in 0..GIT_PER_CLIENT {
956 assert_eq!(limiter.0.check_at("a", now), Decision::Allowed);
957 }
958
959 assert!(matches!(
960 limiter.0.check_at("a", now),
961 Decision::Throttled(_)
962 ));
963 assert_eq!(
964 limiter.0.check_at("b", now),
965 Decision::Allowed,
966 "another client has its own budget"
967 );
968 }
969
970 #[test]
971 fn the_reset_page_gets_a_budget_a_person_can_reload_inside() {
972 // The bug this exists for: six loads of the reset page used to spend most of a
973 // sign-in allowance, so clicking a mailed link a few times locked the reader out
974 // of /auth/login.
975 let limiter = ResetLimiter::default().0;
976
977 for _ in 0..30 {
978 assert!(matches!(limiter.check("a"), Decision::Allowed));
979 }
980 assert!(matches!(limiter.check("a"), Decision::Throttled(_)));
981 assert!(
982 matches!(limiter.check("b"), Decision::Allowed),
983 "another client has its own budget"
984 );
985
986 // And the two budgets are not quietly the same one.
987 assert!(matches!(
988 RateLimiter::default().check("a"),
989 Decision::Allowed
990 ));
991 }
992
993 #[test]
994 fn the_search_limiter_allows_twenty_searches_a_minute_then_refuses() {
995 // The CPU half of the search cap. The 4 MiB reader bounds what one grep can
996 // hand back; this bounds how many greps one address can start.
997 let limiter = SearchLimiter::default().0;
998
999 for _ in 0..SEARCH_PER_CLIENT {
1000 assert!(matches!(limiter.check("a"), Decision::Allowed));
1001 }
1002 assert!(matches!(limiter.check("a"), Decision::Throttled(_)));
1003 assert!(
1004 matches!(limiter.check("b"), Decision::Allowed),
1005 "another client has its own budget"
1006 );
1007 }
1008
1009 #[test]
1010 fn searching_never_spends_the_sign_in_allowance() {
1011 // The reason it is its own limiter rather than a share of an existing one: a
1012 // crawler walking ?q= must not be able to lock the owner out of /auth/login.
1013 let searches = SearchLimiter::default().0;
1014
1015 for _ in 0..SEARCH_GLOBAL {
1016 let _ = searches.check("a");
1017 }
1018
1019 assert!(matches!(
1020 RateLimiter::default().check("a"),
1021 Decision::Allowed
1022 ));
1023 assert!(matches!(
1024 ArchiveLimiter::default().0.check("a"),
1025 Decision::Allowed
1026 ));
1027 }
1028
1029 #[test]
1030 fn the_search_global_window_backstops_a_forged_client_key() {
1031 // Every request a different invented key, which is what a caller who can set
1032 // X-Forwarded-For gets to do. The global window is what still stops it.
1033 let limiter = SearchLimiter::default().0;
1034
1035 for key in 0..SEARCH_GLOBAL {
1036 assert!(matches!(limiter.check(&key.to_string()), Decision::Allowed));
1037 }
1038 assert!(matches!(limiter.check("fresh"), Decision::Throttled(_)));
1039 }
1040}