forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

rate_limit.rs998 lines, 42.9 KiBHistoryRawDownload
1//! Rate limiting, hand-rolled on a fixed 60-second window — no extra crates,
2//! and nothing on the request path but a mutex (the one background task below
3//! only shares counters). The counter is keyed generically: by client IP for the
4//! middleware tiers below, by user id for the per-user chatbot tier
5//! ([`UserRateLimiter`]), which cannot be middleware because the caller is only
6//! known once `CurrentUser` has run.
7//!
8//! Two IP tiers are wired in: a strict one on the credential endpoints
9//! (`/auth/login`, `/auth/register`) in [`crate::web::auth::routes`] to blunt
10//! brute-force and enumeration attempts, and a generous catch-all over the
11//! whole API in [`crate::build_router`]. Those two, and the per-user chat tier,
12//! are all configured per-minute via environment variables (see
13//! [`crate::config::Config`]); a limit of `0` switches that tier off entirely,
14//! which is also what the test suites use to stay unaffected.
15//!
16//! Requests are keyed by client IP. By default that is the peer address of the
17//! TCP connection ([`ConnectInfo`]). Behind a reverse proxy every connection
18//! shows the proxy's address, so set `TRUST_PROXY=true` to key on the
19//! **rightmost entry of the last** `X-Forwarded-For` header instead — that hop
20//! is appended by the nearest proxy and is the only one the client cannot
21//! forge. Both halves matter: a proxy may append its hop as a separate header
22//! line rather than into the client's, and reading only the first line would
23//! hand the key straight back to the client. Never enable it when clients can
24//! reach the server directly: the header is then entirely attacker-controlled
25//! and the limiter is trivially bypassed.
26//!
27//! Fixed windows admit up to a 2× burst straddling a window boundary. That is
28//! an accepted trade-off for an implementation simple enough to read in one
29//! sitting; argon2 keeps each allowed login attempt expensive anyway.
30//!
31//! # Bounding the bucket map
32//!
33//! One client, one bucket, so the map is only as bounded as the client set —
34//! and an IPv6 /64 is not bounded at all. At [`crate::constant::PURGE_AT`] a
35//! new key first sweeps out the lapsed windows and then, if that frees
36//! nothing, evicts down to three quarters of the cap ([`evict_cheapest`]).
37//! Exhausted buckets are exempt from eviction: they are the only ones actually
38//! refusing anyone, and freeing one *raises* the limit for a client that had
39//! reached it. When every bucket is exhausted there is nothing to evict and
40//! the map stays at the cap; the unknown key is then metered against one shared
41//! overflow counter ([`crate::constant::RATE_LIMIT_OVERFLOW_MAX`] per window,
42//! for every keyless client together) instead of getting a bucket.
43//!
44//! Be precise about what that buys, because it is not everyone. A client
45//! **already in the map** keeps its own counter throughout: no flood can starve
46//! it, evict it, or spend its budget, which is the property worth having.
47//! A **newcomer during** the flood is a different story — it never gets a
48//! bucket while the map stays saturated, so *all* of its traffic (not just its
49//! first request) comes out of the one shared budget, and once that budget is
50//! spent every further newcomer is refused. An attacker who first fills the map
51//! and then burns the shared budget therefore does `429` every newcomer for the
52//! rest of the window; `tests/rate_limit.rs` asserts exactly that, ending on a
53//! refused `newcomer-last`.
54//!
55//! That is the accepted trade, not an oversight. The alternative — admitting
56//! keyless clients freely — makes a filled map the way to buy unmetered
57//! throughput from fresh keys, which is an unbounded bypass rather than a
58//! bounded outage, and refusing them outright would hand the attacker the same
59//! `429`-the-newcomers result for free. The shared budget costs an attacker the
60//! flood *plus* [`crate::constant::RATE_LIMIT_OVERFLOW_MAX`] requests a minute,
61//! every minute, to keep it going.
62//!
63//! # The shared window
64//!
65//! The counters above are per process. [`RateLimiter::share`] also carries them
66//! through the process: a background task folds each bucket's new admits into
67//! one shared row per tier + client + wall window (`rate_limit`, see
68//! [`crate::constant::RATE_LIMIT_TABLE`]) every
69//! [`crate::constant::RATE_SYNC_INTERVAL_SECS`], and the stored total that
70//! comes back caps what the local bucket admits for the rest of that window —
71//! so a restart mid-window does not hand every client a fresh budget.
72//!
73//! Admission itself stays in memory and stays synchronous — no request ever
74//! waits on the database to be let in, and a database that is down or slow
75//! costs nothing but the sharing (the tiers fall back to their local budgets
76//! rather than failing anyone). The cost is a lag: a process that has just
77//! started can spend up to its own full budget for one interval before the
78//! shared total tells it to stop.
79
80use std::collections::HashMap;
81use std::hash::Hash;
82use std::net::{IpAddr, Ipv4Addr, SocketAddr};
83use std::sync::{Arc, Mutex, OnceLock};
84use std::time::Duration;
85
86use axum::extract::{ConnectInfo, Request};
87use axum::middleware::Next;
88use axum::response::Response;
89// tokio's `Instant` wraps `std::time::Instant` in production but obeys
90// `tokio::time::pause`/`advance` under `start_paused` tests, which makes the
91// window arithmetic below testable without sleeping.
92use tokio::time::Instant;
93
94use crate::constant::{
95 PURGE_AT, RATE_LIMIT_OVERFLOW_MAX, RATE_SYNC_INTERVAL_SECS, RATE_SYNC_MAX_KEYS,
96 RATE_SYNC_TIMEOUT_SECS,
97};
98use crate::database::Database;
99use crate::domain::timestamp::Timestamp;
100use crate::error::AppError;
101use crate::telemetry::Metrics;
102
103/// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and
104/// carried in [`crate::state::AppState`]. A `0` limit disables that tier.
105#[derive(Clone, Debug)]
106pub struct RateLimitConfig {
107 /// Requests per minute per IP for `/auth/login` + `/auth/register`.
108 pub auth_per_minute: u32,
109 /// Requests per minute per IP for the whole API.
110 pub api_per_minute: u32,
111 /// Key clients by the rightmost `X-Forwarded-For` entry instead of the
112 /// socket peer address. Only safe behind a proxy that appends it.
113 pub trust_proxy: bool,
114}
115
116impl RateLimitConfig {
117 /// Both tiers off. What the test helpers use so unrelated suites never
118 /// trip a limit; dedicated rate-limit tests opt into tight configs.
119 pub const fn unlimited() -> Self {
120 Self {
121 auth_per_minute: 0,
122 api_per_minute: 0,
123 trust_proxy: false,
124 }
125 }
126}
127
128/// A fixed-window counter per caller `K`: `max` requests per `window`, shared
129/// across clones (clones see the same buckets, so one limiter can be captured
130/// by a middleware closure and cloned per request for free).
131#[derive(Clone)]
132pub struct RateLimiter<K = IpAddr> {
133 max: u32,
134 window: Duration,
135 /// Only meaningful for the IP tiers; the keyed tiers never look at it.
136 trust_proxy: bool,
137 buckets: Arc<Mutex<HashMap<K, Bucket>>>,
138 /// What this tier is called in telemetry (`api`, `auth`, `chatbot`,
139 /// `builder`). Named by [`RateLimiter::share`], which is where the tier's
140 /// name already lives — the constructors take a number and nothing else,
141 /// and every tier the router builds is shared. Shared with the clones, so
142 /// the middleware's clone sees the name too.
143 tier: Arc<OnceLock<&'static str>>,
144 /// The single bucket every client shares once the map is saturated and no
145 /// eviction is allowed (see the module docs). Local only: it is keyless, so
146 /// it is never synced to the shared table.
147 overflow: Arc<Mutex<Bucket>>,
148}
149
150struct Bucket {
151 window_start: Instant,
152 /// Requests this process admitted in the current local window.
153 count: u32,
154 /// How many of `count` are accounted for against the *current* shared row
155 /// — folded into it, or charged to an earlier one before the wall window
156 /// rolled. Never above `count`, so `count - pushed` is what is still ours
157 /// to report.
158 pushed: u32,
159 /// The stored total the last sync read back — every admit in this wall
160 /// window, our `pushed` share included. Zero until a sync lands, which is
161 /// what makes an unshared limiter behave exactly like the local-only one it
162 /// replaced.
163 remote: u32,
164 /// The wall window (`RATE_LIMIT_TABLE` row) `pushed`/`remote` describe, or
165 /// `None` until the first sync. The local window rolls per client while the
166 /// shared one is aligned to the clock, so this says which shared row those
167 /// two numbers came from.
168 epoch: Option<i64>,
169}
170
171impl Bucket {
172 /// A fresh window: nothing admitted, nothing shared, nothing known.
173 fn opened_at(now: Instant) -> Self {
174 Self {
175 window_start: now,
176 count: 0,
177 pushed: 0,
178 remote: 0,
179 epoch: None,
180 }
181 }
182
183 /// Requests spent as far as this process can tell: what the shared row held
184 /// at the last sync — this process's earlier life included — plus our own
185 /// admits since, and never less than this local window's own count. Equals
186 /// `count` until a sync lands.
187 ///
188 /// The local floor is what a wall-window roll needs: the admits it moves
189 /// out of the shared reckoning (they belong to the row that has passed)
190 /// must not come back as fresh budget inside a local window that is still
191 /// running.
192 fn spent(&self) -> u32 {
193 self.count
194 .max(self.remote.saturating_add(self.count - self.pushed))
195 }
196}
197
198impl<K> RateLimiter<K> {
199 /// This tier's telemetry name, or `unnamed` for a limiter nobody shared
200 /// (tests build those; the router shares every tier it wires).
201 fn tier(&self) -> &'static str {
202 self.tier.get().copied().unwrap_or("unnamed")
203 }
204
205 /// One refusal, counted for the operator. Deliberately *only* a counter:
206 /// a log line per rejection is a flood amplifier, and the only fields
207 /// worth having (who, from where) are the ones telemetry may not carry.
208 fn count_rejection(&self) {
209 Metrics::global()
210 .rate_limit_rejections_total
211 .add(1, &[opentelemetry::KeyValue::new("tier", self.tier())]);
212 }
213
214 /// Requests allowed per window, `0` meaning the tier is off. Read by
215 /// `GET /limits` so a client learns its own budget instead of discovering
216 /// it by getting a `429`.
217 pub fn max_per_window(&self) -> u32 {
218 self.max
219 }
220}
221
222/// The per-user tier, keyed by user id instead of client IP. Lives in
223/// [`crate::state::AppState`] and is called from inside a handler, after
224/// `CurrentUser` has identified the caller.
225pub type UserRateLimiter = RateLimiter<String>;
226
227impl Default for UserRateLimiter {
228 /// The chatbot tier at its shipped default, for tests and any caller that
229 /// has no [`crate::config::Config`] to hand.
230 fn default() -> Self {
231 Self::per_user_minute(crate::constant::DEFAULT_CHATBOT_RATE_LIMIT)
232 }
233}
234
235impl UserRateLimiter {
236 /// The chatbot tier: `max` messages per user per minute, from
237 /// `RATE_LIMIT_CHATBOT_PER_MINUTE`. `max == 0` disables it, like the IP tiers.
238 pub fn per_user_minute(max: u32) -> Self {
239 Self::new(max, false)
240 }
241
242 /// Count one message from `user_id`, answering `429` with a `Retry-After`
243 /// once the user is over the cap. The handler-side twin of [`RateLimiter::enforce`].
244 pub fn enforce_user(&self, user_id: &str) -> Result<(), AppError> {
245 self.check(user_id.to_string()).map_err(|retry_after_secs| {
246 tracing::warn!(retry_after_secs, "per-user rate limit exceeded");
247 AppError::TooManyRequests { retry_after_secs }
248 })
249 }
250}
251
252impl RateLimiter<IpAddr> {
253 /// A limiter allowing `max` requests per fixed one-minute window. `max == 0`
254 /// means disabled: every check passes and nothing is recorded.
255 pub fn per_minute(max: u32, trust_proxy: bool) -> Self {
256 Self::new(max, trust_proxy)
257 }
258
259 /// Axum middleware entry point: identify the caller, count the request,
260 /// and either pass it along or answer `429` with a `Retry-After`.
261 pub async fn enforce(&self, req: Request, next: Next) -> Result<Response, AppError> {
262 let ip = client_ip(&req, self.trust_proxy);
263 match self.check(ip) {
264 Ok(()) => Ok(next.run(req).await),
265 Err(retry_after_secs) => {
266 tracing::warn!(retry_after_secs, "rate limit exceeded");
267 Err(AppError::TooManyRequests { retry_after_secs })
268 }
269 }
270 }
271}
272
273impl<K: Eq + Hash> RateLimiter<K> {
274 /// A limiter allowing `max` requests per fixed one-minute window.
275 fn new(max: u32, trust_proxy: bool) -> Self {
276 Self {
277 max,
278 window: Duration::from_secs(60),
279 trust_proxy,
280 buckets: Arc::new(Mutex::new(HashMap::new())),
281 tier: Arc::new(OnceLock::new()),
282 overflow: Arc::new(Mutex::new(Bucket::opened_at(Instant::now()))),
283 }
284 }
285
286 /// Meter one keyless request against the shared overflow budget. Same fixed
287 /// window as a real bucket, one counter for everyone who lands here.
288 fn check_overflow(&self, now: Instant) -> Result<(), u64> {
289 let mut bucket = self.overflow.lock().expect("rate limiter mutex poisoned");
290 if now.duration_since(bucket.window_start) >= self.window {
291 *bucket = Bucket::opened_at(now);
292 }
293 // `count` and not `spent()`: nothing shared ever reaches this bucket.
294 if bucket.count < RATE_LIMIT_OVERFLOW_MAX {
295 bucket.count += 1;
296 return Ok(());
297 }
298 let remaining = self.window - now.duration_since(bucket.window_start);
299 Err((remaining.as_secs_f64().ceil() as u64).max(1))
300 }
301
302 /// [`RateLimiter::check_key`], counting whatever it refuses. Every tier's
303 /// rejections pass through here — both `enforce` paths and the overflow
304 /// budget — so the counter cannot miss one.
305 fn check(&self, key: K) -> Result<(), u64> {
306 self.check_key(key).inspect_err(|_| self.count_rejection())
307 }
308
309 /// Count one request from `key`. `Err` carries the whole seconds (rounded
310 /// up, at least 1) until the window resets — the `Retry-After` value.
311 fn check_key(&self, key: K) -> Result<(), u64> {
312 if self.max == 0 {
313 return Ok(());
314 }
315
316 let now = Instant::now();
317 let mut buckets = self.buckets.lock().expect("rate limiter mutex poisoned");
318
319 // Only a *new* key can grow the map, so only a new key pays for a sweep
320 // — a client already in there stays one hash lookup, saturated or not.
321 // corner-cut: while the map is saturated every new key still pays one
322 // O(n) scan. Ceiling: it takes 10k live exhausted clients to get there
323 // and the scan is the attacker's own request. Upgrade path: keep the
324 // earliest `window_start` beside the map and skip the scan until then.
325 if buckets.len() >= PURGE_AT && !buckets.contains_key(&key) {
326 buckets.retain(|_, b| now.duration_since(b.window_start) < self.window);
327 // Lapsed buckets alone are no bound: enough distinct clients inside
328 // one window (one IPv6 /64 is enough) frees nothing, and the map
329 // would grow while every request paid for the scan.
330 if buckets.len() >= PURGE_AT {
331 evict_cheapest(&mut buckets, PURGE_AT - PURGE_AT / 4, self.max);
332 }
333 if buckets.len() >= PURGE_AT {
334 // Every bucket left is exhausted and none may be dropped. This
335 // key gets no bucket, but it is still metered: everyone in that
336 // position shares one aggregate counter. Refusing outright
337 // would 429 every newcomer for free; admitting freely would
338 // make a saturated map the bypass. Clients already in the map
339 // are untouched either way (see the module docs).
340 drop(buckets);
341 return self.check_overflow(now);
342 }
343 }
344
345 let bucket = buckets.entry(key).or_insert_with(|| Bucket::opened_at(now));
346 if now.duration_since(bucket.window_start) >= self.window {
347 // A fresh window starts owing nothing and knowing nothing: keeping
348 // the old total would hold the client at a budget it no longer
349 // spent. The next sync re-reads what the fleet has spent since.
350 *bucket = Bucket::opened_at(now);
351 }
352
353 if bucket.spent() < self.max {
354 bucket.count += 1;
355 Ok(())
356 } else {
357 let remaining = self.window - now.duration_since(bucket.window_start);
358 Err((remaining.as_secs_f64().ceil() as u64).max(1))
359 }
360 }
361}
362
363/// Drop buckets until at most `target` remain, cheapest first, and **never** a
364/// bucket that has spent `max` or more.
365///
366/// The exemption is the whole point. An exhausted bucket is the only thing in
367/// here actually refusing anyone, and evicting it hands that refusal straight
368/// back to whoever earned it. Cheapest-first alone does not protect it: the
369/// cutoff is a `<=`, so ties go arbitrarily, and an attacker who drives every
370/// flood key to exactly the victim's spend puts the victim inside the tie band
371/// (measured: a victim at `max` freed after ~12.5k flood keys). Exhaustion,
372/// not rank, is what decides.
373///
374/// Among the rest, least-spent-first: those are the throwaway keys a flood is
375/// made of, and evicting one gives away only what it had spent. Evicting by
376/// age would instead pick out long-running buckets, which is backwards.
377///
378/// One pass over the map, and only when a new key arrives at the cap: the
379/// target sits a quarter below it, so the sweep is amortised over that many
380/// further inserts and the common path stays a single hash lookup.
381fn evict_cheapest<K: Eq + Hash>(buckets: &mut HashMap<K, Bucket>, target: usize, max: u32) {
382 let Some(excess) = buckets.len().checked_sub(target).filter(|n| *n > 0) else {
383 return;
384 };
385 let mut spent: Vec<u32> = buckets
386 .values()
387 .map(Bucket::spent)
388 .filter(|spent| *spent < max)
389 .collect();
390 // Nothing but exhausted buckets: the caller decides what to do instead.
391 let Some(excess) = Some(excess.min(spent.len())).filter(|n| *n > 0) else {
392 return;
393 };
394 // The `excess`-th smallest spend among the evictable: at least `excess`
395 // buckets are at or under it, which is what makes the budgeted retain
396 // below drop exactly `excess`.
397 let (_, &mut cutoff, _) = spent.select_nth_unstable(excess - 1);
398 let mut budget = excess;
399 buckets.retain(|_, b| {
400 let spent = b.spent();
401 let evict = budget > 0 && spent < max && spent <= cutoff;
402 budget -= usize::from(evict);
403 !evict
404 });
405}
406
407/// One bucket's report, taken while the map was locked so the round can run
408/// its query without holding it. `counted` is the `count` the delta was read
409/// from — a request admitted mid-round bumps `count` past it and is simply
410/// carried into the next round.
411struct Pending<K> {
412 key: K,
413 delta: u32,
414 counted: u32,
415 window_start: Instant,
416}
417
418impl<K> RateLimiter<K>
419where
420 K: Eq + Hash + Clone + std::fmt::Display + Send + Sync + 'static,
421{
422 /// Make this tier's budget outlive the process: every
423 /// [`RATE_SYNC_INTERVAL_SECS`] a background task reports what this limiter
424 /// has admitted and reads back the window's total, which caps further local
425 /// admits in the same window (see the module docs).
426 ///
427 /// `tier` names the counter's namespace in the shared table — two limiters
428 /// sharing a name share a budget, which is exactly what the two processes
429 /// running the same tier want and what `auth` and `api` must avoid.
430 ///
431 /// The task holds a *weak* reference to the buckets, so it stops with the
432 /// limiter rather than keeping a dropped one alive (test suites build
433 /// dozens).
434 pub fn share(&self, tier: &'static str, db: Database) {
435 self.share_windowed(tier, db, None);
436 }
437
438 /// [`RateLimiter::share`] with the wall window pinned, for tests only.
439 ///
440 /// A round reads the real clock, so any assertion about *the* shared row
441 /// is otherwise a bet that the run does not cross a minute mid-round —
442 /// two limiters of one tier would then report into two rows and neither
443 /// would see the other's spend. An accidental relationship to the wall
444 /// clock is precisely what kept the epoch-roll double-charge out of
445 /// `tests/rate_limit.rs`, so the sharing tests choose their window instead.
446 pub fn share_pinned(&self, tier: &'static str, db: Database, epoch: i64) {
447 self.share_windowed(tier, db, Some(epoch));
448 }
449
450 fn share_windowed(&self, tier: &'static str, db: Database, pinned: Option<i64>) {
451 // Before the early return: a disabled tier still wants its name, so a
452 // limiter turned on later reports under it.
453 let _ = self.tier.set(tier);
454 if self.max == 0 {
455 // The tier is off: `check` records nothing, so there is nothing to
456 // share and no reason to hold a task or a table row.
457 return;
458 }
459 let buckets = Arc::downgrade(&self.buckets);
460 let window = self.window;
461 tokio::spawn(async move {
462 let mut swept = 0;
463 loop {
464 tokio::time::sleep(Duration::from_secs(RATE_SYNC_INTERVAL_SECS)).await;
465 let Some(buckets) = buckets.upgrade() else {
466 return;
467 };
468 // `with_deadline` bounds every round, so an outage costs the
469 // sharing nothing but skipped rounds: local budgets keep
470 // admitting and the deltas ride the first round after recovery.
471 let epoch = pinned.unwrap_or_else(|| current_epoch(window));
472 sync_once(tier, &buckets, window, epoch, &db).await;
473 // Piggybacked cleanup, once per window: rows for a window that
474 // has passed can never be read again.
475 if swept != epoch {
476 swept = epoch;
477 if let Err(err) = with_deadline(
478 sqlx::query("DELETE FROM rate_limit WHERE window_start < $1")
479 .bind(epoch)
480 .execute(&db),
481 )
482 .await
483 {
484 tracing::warn!(%err, "rate-limit sweep failed; retrying next window");
485 }
486 }
487 }
488 });
489 }
490}
491
492/// Fold every live bucket's new admits into their shared rows and take the
493/// window's totals back.
494///
495/// The whole round is one statement: `INSERT … ON CONFLICT (id) DO UPDATE SET
496/// hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits`, so a fold is
497/// atomic — the old engine could fail one bucket's statement inside a round,
498/// Postgres cannot fail half a statement. A round that fails (deadline,
499/// outage) lands nothing: every bucket keeps its delta unreported and the
500/// next round (2s later) carries it, which is why no retry loop is needed
501/// here. Retrying the *statement* would double-apply the hits that landed,
502/// since the fold accumulates — skipping a round is the only honest failure.
503async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>(
504 tier: &str,
505 buckets: &Mutex<HashMap<K, Bucket>>,
506 window: Duration,
507 epoch: i64,
508 db: &Database,
509) {
510 let now = Instant::now();
511 let pending: Vec<Pending<K>> = {
512 let mut guard = buckets.lock().expect("rate limiter mutex poisoned");
513 guard
514 .iter_mut()
515 .filter(|(_, b)| b.count > 0 && now.duration_since(b.window_start) < window)
516 .take(RATE_SYNC_MAX_KEYS)
517 .map(|(key, b)| {
518 if b.epoch != Some(epoch) {
519 // A different shared row from the one `pushed`/`remote`
520 // describe: that total is about a window that has passed.
521 // What was already charged to it must not be charged again
522 // here — every local window straddles a boundary, so
523 // re-reporting the whole count would bill each of those
524 // requests to two rows and spend the client's next budget
525 // before it began. Only a bucket that has never synced owes
526 // its whole count, having been billed nowhere yet.
527 //
528 // corner-cut: admits between the boundary and this round land
529 // on the old row. Ceiling: RATE_SYNC_INTERVAL_SECS of one
530 // client's traffic, charged once either way. Upgrade path:
531 // stamp each admit with its epoch.
532 if b.epoch.is_some() {
533 b.pushed = b.count;
534 }
535 b.epoch = Some(epoch);
536 b.remote = 0;
537 }
538 Pending {
539 key: key.clone(),
540 delta: b.count - b.pushed,
541 counted: b.count,
542 window_start: b.window_start,
543 }
544 })
545 .collect()
546 };
547 if pending.is_empty() {
548 return;
549 }
550
551 // One statement for the whole round. A row's id pins its wall window
552 // (`row_key` folds the epoch in), so a conflict can only be another
553 // limiter of the same tier folding the same client inside the same window
554 // — the ON CONFLICT fold is exactly the replay that must add, not clobber.
555 let mut fold = sqlx::QueryBuilder::<sqlx::Postgres>::new(
556 "INSERT INTO rate_limit (id, hits, window_start) ",
557 );
558 fold.push_values(pending.iter(), |mut b, p| {
559 b.push_bind(row_key(tier, &p.key, epoch))
560 .push_bind(i64::from(p.delta))
561 .push_bind(epoch);
562 });
563 fold.push(
564 " ON CONFLICT (id) DO UPDATE SET hits = rate_limit.hits + EXCLUDED.hits RETURNING id, hits",
565 );
566 let rows: Vec<(String, i64)> = match with_deadline(fold.build_query_as().fetch_all(db)).await {
567 Ok(rows) => rows,
568 Err(err) => {
569 tracing::warn!(%err, tier, "rate-limit sync failed; counting locally until it recovers");
570 return;
571 }
572 };
573 let totals: HashMap<String, i64> = rows.into_iter().collect();
574
575 let mut guard = buckets.lock().expect("rate limiter mutex poisoned");
576 for p in &pending {
577 // A row missing from the fold's answer stands in for the failed
578 // statement it replaces: its bucket stays untouched, the delta stays
579 // unreported, and the next round carries it.
580 let Some(total) = totals.get(&row_key(tier, &p.key, epoch)) else {
581 continue;
582 };
583 let Some(bucket) = guard.get_mut(&p.key) else {
584 continue;
585 };
586 // The window may have rolled while the query was in flight, in which
587 // case this total is about a bucket that no longer exists.
588 if bucket.epoch != Some(epoch) || bucket.window_start != p.window_start {
589 continue;
590 }
591 bucket.pushed = p.counted;
592 bucket.remote = (*total).clamp(0, u32::MAX.into()) as u32;
593 }
594}
595
596/// The wall-clock window a shared row is keyed by, aligned so a restarted
597/// process lands on the same one — the local windows cannot be used for this,
598/// since each starts whenever that client's first request happened to land.
599fn current_epoch(window: Duration) -> i64 {
600 let ms = i64::try_from(window.as_millis()).unwrap_or(i64::MAX).max(1);
601 Timestamp::now().as_millis().div_euclid(ms) * ms
602}
603
604/// The shared row's key: tier, client, window. The client part is hashed
605/// because it is a raw IP or user id — free of the `:` and `_` that would
606/// otherwise let one client's key collide with another's by construction.
607fn row_key<K: std::fmt::Display>(tier: &str, key: &K, epoch: i64) -> String {
608 use sha2::{Digest, Sha256};
609 let digest = Sha256::digest(key.to_string().as_bytes());
610 format!("{tier}_{:x}_{epoch}", ByteSlice(&digest[..8]))
611}
612
613/// Lowercase hex of a byte slice, for [`row_key`].
614struct ByteSlice<'a>(&'a [u8]);
615
616impl std::fmt::LowerHex for ByteSlice<'_> {
617 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
618 self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
619 }
620}
621
622/// Run one sync statement under a deadline. Postgres fails a dead connection
623/// instead of parking the query, but a slow or overloaded server can still
624/// stall a round past what the sharing can afford — every tier's budget rides
625/// this one task, so a wedged round would stall all of them. A dropped round
626/// leaves its deltas unreported and the next round carries them.
627async fn with_deadline<T, Fut>(query: Fut) -> Result<T, AppError>
628where
629 Fut: Future<Output = Result<T, sqlx::Error>>,
630{
631 tokio::time::timeout(Duration::from_secs(RATE_SYNC_TIMEOUT_SECS), query)
632 .await
633 .map_err(|_| AppError::Internal("rate-limit sync timed out".into()))?
634 .map_err(AppError::from)
635}
636
637/// Resolve the client IP a request is billed against.
638///
639/// With `trust_proxy`, prefer the rightmost entry of the *last*
640/// `X-Forwarded-For` header — appended by the nearest (trusted) proxy, unlike
641/// the left entries and the earlier header lines, which arrive
642/// attacker-controlled (a proxy that appends its own header line instead of
643/// extending the client's leaves the client's line first). Earlier lines are
644/// only consulted if the last one is empty or unparseable; if none yield an
645/// address (or the header is missing) fall back to the connection's peer
646/// address. `oneshot`-driven routers carry no [`ConnectInfo`]; those requests
647/// share the unspecified-address bucket.
648fn client_ip(req: &Request, trust_proxy: bool) -> IpAddr {
649 if trust_proxy
650 && let Some(ip) = req
651 .headers()
652 .get_all("x-forwarded-for")
653 .iter()
654 .rev()
655 .find_map(|v| v.to_str().ok()?.rsplit(',').next()?.trim().parse().ok())
656 {
657 return ip;
658 }
659
660 req.extensions()
661 .get::<ConnectInfo<SocketAddr>>()
662 .map(|ci| ci.0.ip())
663 .unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED))
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669 use axum::body::Body;
670
671 fn ip(last: u8) -> IpAddr {
672 IpAddr::V4(Ipv4Addr::new(10, 0, 0, last))
673 }
674
675 /// A request with an optional `X-Forwarded-For` header and an optional
676 /// peer address, mirroring what a real connection / a proxy would produce.
677 fn req(xff: Option<&str>, peer: Option<&str>) -> Request {
678 let mut builder = axum::http::Request::builder().uri("/");
679 if let Some(v) = xff {
680 builder = builder.header("x-forwarded-for", v);
681 }
682 let mut req = builder.body(Body::empty()).unwrap();
683 if let Some(addr) = peer {
684 let addr: SocketAddr = addr.parse().unwrap();
685 req.extensions_mut().insert(ConnectInfo(addr));
686 }
687 req
688 }
689
690 #[tokio::test]
691 async fn client_ip_takes_rightmost_forwarded_hop_when_proxy_is_trusted() {
692 let request = req(Some("1.1.1.1, 2.2.2.2"), Some("10.9.8.7:443"));
693 assert_eq!(
694 client_ip(&request, true),
695 "2.2.2.2".parse::<IpAddr>().unwrap()
696 );
697
698 let single = req(Some("2001:db8::7"), Some("10.9.8.7:443"));
699 assert_eq!(
700 client_ip(&single, true),
701 "2001:db8::7".parse::<IpAddr>().unwrap()
702 );
703 }
704
705 /// A proxy that appends its hop as its own header line instead of
706 /// extending the client's: the client's line comes first and is entirely
707 /// forged, so only the last line may be billed.
708 #[tokio::test]
709 async fn client_ip_takes_the_last_forwarded_header_line() {
710 let two_lines = |first: &str, last: &str| {
711 axum::http::Request::builder()
712 .uri("/")
713 .header("x-forwarded-for", first)
714 .header("x-forwarded-for", last)
715 .body(Body::empty())
716 .unwrap()
717 };
718
719 assert_eq!(
720 client_ip(&two_lines("1.1.1.1, 6.6.6.6", "9.9.9.9"), true),
721 "9.9.9.9".parse::<IpAddr>().unwrap()
722 );
723 // An unusable last line falls back through the earlier ones before it
724 // gives up on the header entirely.
725 assert_eq!(
726 client_ip(&two_lines("1.1.1.1, 6.6.6.6", "not-an-ip"), true),
727 "6.6.6.6".parse::<IpAddr>().unwrap()
728 );
729 }
730
731 #[tokio::test]
732 async fn client_ip_ignores_forwarded_header_when_proxy_is_untrusted() {
733 let request = req(Some("1.1.1.1"), Some("10.9.8.7:443"));
734 assert_eq!(
735 client_ip(&request, false),
736 "10.9.8.7".parse::<IpAddr>().unwrap()
737 );
738 }
739
740 #[tokio::test]
741 async fn client_ip_falls_back_to_peer_on_unparseable_forwarded_entries() {
742 // Not an address at all, and the `ip:port` form some proxies emit —
743 // neither may be billed as a distinct client.
744 for garbage in ["not-an-ip", "1.2.3.4:5678", ""] {
745 let request = req(Some(garbage), Some("10.9.8.7:443"));
746 assert_eq!(
747 client_ip(&request, true),
748 "10.9.8.7".parse::<IpAddr>().unwrap(),
749 "{garbage:?} must fall back to the peer address"
750 );
751 }
752 }
753
754 #[tokio::test]
755 async fn client_ip_is_unspecified_without_any_connection_info() {
756 // `oneshot`-driven requests: no header, no peer. Everyone shares 0.0.0.0.
757 let request = req(None, None);
758 assert_eq!(client_ip(&request, true), IpAddr::V4(Ipv4Addr::UNSPECIFIED));
759 }
760
761 #[tokio::test(start_paused = true)]
762 async fn allows_up_to_max_then_rejects() {
763 let limiter = RateLimiter::per_minute(3, false);
764 for _ in 0..3 {
765 assert!(limiter.check(ip(1)).is_ok());
766 }
767 assert!(limiter.check(ip(1)).is_err());
768 }
769
770 /// The boundary is exact at realistic limits too, the shipped defaults
771 /// included: request `max` passes, request `max + 1` is rejected — never
772 /// an off-by-one in either direction.
773 #[tokio::test(start_paused = true)]
774 async fn boundary_is_exact_at_production_scale_limits() {
775 use crate::constant::{DEFAULT_API_RATE_LIMIT, DEFAULT_AUTH_RATE_LIMIT};
776
777 for max in [1, DEFAULT_AUTH_RATE_LIMIT, 50, DEFAULT_API_RATE_LIMIT] {
778 let limiter = RateLimiter::per_minute(max, false);
779 for n in 1..=max {
780 assert_eq!(
781 limiter.check(ip(1)),
782 Ok(()),
783 "request {n}/{max} must be admitted"
784 );
785 }
786 assert_eq!(
787 limiter.check(ip(1)),
788 Err(60),
789 "request {}/{max} must be rejected",
790 max + 1
791 );
792 }
793 }
794
795 #[tokio::test(start_paused = true)]
796 async fn window_resets_after_a_minute() {
797 let limiter = RateLimiter::per_minute(1, false);
798 assert!(limiter.check(ip(1)).is_ok());
799 assert!(limiter.check(ip(1)).is_err());
800
801 tokio::time::advance(Duration::from_secs(60)).await;
802 assert!(limiter.check(ip(1)).is_ok());
803 }
804
805 #[tokio::test(start_paused = true)]
806 async fn retry_after_counts_down_and_never_hits_zero() {
807 let limiter = RateLimiter::per_minute(1, false);
808 assert!(limiter.check(ip(1)).is_ok());
809 assert_eq!(limiter.check(ip(1)), Err(60));
810
811 tokio::time::advance(Duration::from_secs(45)).await;
812 assert_eq!(limiter.check(ip(1)), Err(15));
813
814 // 59.5s in: 0.5s remain, which must round up to 1, not down to 0.
815 tokio::time::advance(Duration::from_millis(14_500)).await;
816 assert_eq!(limiter.check(ip(1)), Err(1));
817 }
818
819 #[tokio::test(start_paused = true)]
820 async fn ips_get_independent_buckets() {
821 let limiter = RateLimiter::per_minute(1, false);
822 assert!(limiter.check(ip(1)).is_ok());
823 assert!(limiter.check(ip(1)).is_err());
824 assert!(limiter.check(ip(2)).is_ok());
825 }
826
827 /// The keyed tier the chatbot handler calls: users are metered
828 /// independently, refused past the cap, and freed again a minute later.
829 #[tokio::test(start_paused = true)]
830 async fn users_get_independent_windows_that_reset() {
831 let limiter = UserRateLimiter::default();
832 for _ in 0..crate::constant::DEFAULT_CHATBOT_RATE_LIMIT {
833 assert!(limiter.enforce_user("user:a").is_ok());
834 }
835 assert!(matches!(
836 limiter.enforce_user("user:a"),
837 Err(AppError::TooManyRequests {
838 retry_after_secs: 60
839 })
840 ));
841 assert!(
842 limiter.enforce_user("user:b").is_ok(),
843 "another user must not inherit a's window"
844 );
845
846 tokio::time::advance(Duration::from_secs(60)).await;
847 assert!(limiter.enforce_user("user:a").is_ok());
848 }
849
850 #[tokio::test(start_paused = true)]
851 async fn zero_means_disabled() {
852 let limiter = RateLimiter::per_minute(0, false);
853 for _ in 0..1_000 {
854 assert!(limiter.check(ip(1)).is_ok());
855 }
856 assert!(limiter.buckets.lock().unwrap().is_empty());
857 }
858
859 #[tokio::test(start_paused = true)]
860 async fn stale_buckets_are_purged_once_map_is_large() {
861 let limiter = RateLimiter::per_minute(5, false);
862 for i in 0..PURGE_AT as u32 {
863 let addr = IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + i));
864 assert!(limiter.check(addr).is_ok());
865 }
866 assert_eq!(limiter.buckets.lock().unwrap().len(), PURGE_AT);
867
868 // All those windows lapse; the next *new* client sweeps them out (only
869 // a key that would grow the map pays for a sweep — 10.x is taken above,
870 // so the new client has to come from somewhere else).
871 tokio::time::advance(Duration::from_secs(61)).await;
872 let newcomer = IpAddr::V4(Ipv4Addr::new(172, 16, 0, 1));
873 assert!(limiter.check(newcomer).is_ok());
874 assert_eq!(limiter.buckets.lock().unwrap().len(), 1);
875 }
876
877 /// The bound has to hold when *nothing* has lapsed — the sweep above frees
878 /// nothing then, and one IPv6 /64 supplies all the live keys it takes. The
879 /// eviction must spend itself on the throwaway keys, never on the
880 /// exhausted bucket that the flood is trying to buy a fresh window for.
881 #[tokio::test(start_paused = true)]
882 async fn live_buckets_are_evicted_so_the_map_stays_bounded() {
883 let limiter = RateLimiter::per_minute(5, false);
884 for _ in 0..5 {
885 assert!(limiter.check(ip(1)).is_ok());
886 }
887 assert!(limiter.check(ip(1)).is_err(), "victim starts exhausted");
888
889 // Twice the threshold in distinct clients, all inside one window.
890 for i in 0..2 * PURGE_AT as u32 {
891 let addr = IpAddr::V4(Ipv4Addr::from(0x0b00_0000 + i));
892 assert!(limiter.check(addr).is_ok());
893 assert!(
894 limiter.buckets.lock().unwrap().len() <= PURGE_AT,
895 "map grew past the cap at client {i}"
896 );
897 }
898
899 assert!(
900 limiter.check(ip(1)).is_err(),
901 "the flood must not have bought the exhausted bucket a fresh window"
902 );
903 }
904
905 /// The flood above was cheap to tell apart. This one is not: every flood
906 /// key is driven to *exactly* the spend of the bucket it is trying to
907 /// free, so a cheapest-first cutoff of `<=` puts the victim inside the tie
908 /// band and picks arbitrarily. Nothing that has reached its limit may be
909 /// evicted, whoever else shares its spend — a limiter that forgets an
910 /// exhausted bucket fails open, which is worse than the unbounded map.
911 #[tokio::test(start_paused = true)]
912 async fn a_flood_at_the_victims_own_spend_frees_nobody() {
913 const MAX: u32 = 5;
914 let limiter = RateLimiter::per_minute(MAX, false);
915 // Every key here is driven to exhaustion, the named victim first.
916 let keys: Vec<IpAddr> = std::iter::once(ip(1))
917 .chain((0..PURGE_AT as u32).map(|i| IpAddr::V4(Ipv4Addr::from(0x0b00_0000 + i))))
918 .collect();
919 for key in &keys {
920 for _ in 0..MAX {
921 assert!(limiter.check(*key).is_ok());
922 }
923 }
924
925 assert!(
926 limiter.buckets.lock().unwrap().len() <= PURGE_AT,
927 "map grew past the cap"
928 );
929
930 // The first `PURGE_AT` keys — the victim among them — filled the map
931 // before it saturated, so every one of them was metered all the way to
932 // its limit and every one of them must still be refused. An eviction
933 // that dropped an exhausted bucket shows up right here, as an admit.
934 for key in &keys[..PURGE_AT] {
935 assert!(
936 limiter.check(*key).is_err(),
937 "{key} was exhausted and is being served again"
938 );
939 }
940 }
941
942 /// How many of `tries` requests the limiter admits for `user`.
943 fn admits(limiter: &UserRateLimiter, user: &str, tries: usize) -> usize {
944 (0..tries)
945 .filter(|_| limiter.enforce_user(user).is_ok())
946 .count()
947 }
948
949 /// A wall-window roll must not bill one request to two shared rows: the
950 /// fold reports only a bucket's *unreported* delta, so when the wall
951 /// window rolls under a still-live local window, the new row receives
952 /// nothing the old row had already taken. (Rebuilt over the control
953 /// database — `rate_limit` is a control table — after the SurrealDB port
954 /// dropped it along with the embedded engine.)
955 #[tokio::test]
956 async fn a_wall_epoch_roll_charges_no_request_twice() {
957 const MAX: u32 = 5;
958 let tenants = crate::database::init_test_tenants().await;
959 let db = tenants.control().clone();
960 let limiter = UserRateLimiter::per_user_minute(MAX);
961 let window = Duration::from_secs(60);
962 let epoch = current_epoch(window);
963 assert_eq!(window.as_millis() as i64, 60_000, "epochs are 60s apart");
964
965 // A burst early in the client's local window, folded into row `epoch`.
966 for _ in 0..MAX {
967 assert!(limiter.enforce_user("user:a").is_ok());
968 }
969 sync_once("test", &limiter.buckets, window, epoch, &db).await;
970
971 // The wall clock rolls while that local window is still running.
972 sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await;
973
974 // The local window lapses, so the client opens a fresh one — inside
975 // the *same* new wall window — and spends one request in it.
976 tokio::time::pause();
977 tokio::time::advance(Duration::from_secs(61)).await;
978 tokio::time::resume();
979 assert_eq!(admits(&limiter, "user:a", 1), 1, "a fresh local window");
980 sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await;
981
982 let rows =
983 sqlx::query_scalar::<_, i64>("SELECT hits FROM rate_limit ORDER BY window_start")
984 .fetch_all(&db)
985 .await
986 .expect("read shared counters");
987 assert_eq!(
988 rows,
989 vec![i64::from(MAX), 1],
990 "the new wall row may hold only what was admitted inside it"
991 );
992 assert_eq!(
993 admits(&limiter, "user:a", 4),
994 4,
995 "the client spent 1 of {MAX} in this window and must keep the rest"
996 );
997 }
998}