Skip to main content

interloper_server/
ratelimit.rs

1//! Token buckets, keyed so one noisy client cannot spend another's budget.
2//!
3//! A *valid* API key gets its own bucket per client address. An invalid or
4//! missing key buckets on the address alone: the header is attacker-controlled
5//! before auth runs, so if any header value bought its own bucket, rotating a
6//! bogus key per request would mint a fresh bucket each time and leave
7//! unauthenticated floods unmetered.
8
9use std::collections::HashMap;
10use std::sync::Mutex;
11use std::time::{Duration, Instant};
12
13pub struct Limiter {
14    capacity: f64,
15    per_sec: f64,
16    buckets: Mutex<HashMap<String, (f64, Instant)>>,
17}
18
19impl Limiter {
20    pub fn new(n: u32, window: Duration) -> Self {
21        Limiter {
22            capacity: n as f64,
23            per_sec: n as f64 / window.as_secs_f64(),
24            buckets: Mutex::new(HashMap::new()),
25        }
26    }
27
28    pub fn allow(&self, key: &str) -> bool {
29        self.allow_at(key, Instant::now())
30    }
31
32    fn allow_at(&self, key: &str, now: Instant) -> bool {
33        let mut b = self.buckets.lock().unwrap();
34        // Bound memory: drop buckets that have fully refilled.
35        if b.len() > 50_000 {
36            let full = self.capacity / self.per_sec;
37            b.retain(|_, (_, at)| now.duration_since(*at).as_secs_f64() < full);
38        }
39        let (tokens, at) = b.entry(key.to_string()).or_insert((self.capacity, now));
40        let refill = now.duration_since(*at).as_secs_f64() * self.per_sec;
41        *tokens = (*tokens + refill).min(self.capacity);
42        *at = now;
43        if *tokens >= 1.0 {
44            *tokens -= 1.0;
45            true
46        } else {
47            false
48        }
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn bucket_drains_and_refills() {
58        let l = Limiter::new(2, Duration::from_secs(60));
59        let t = Instant::now();
60        assert!(l.allow_at("a", t));
61        assert!(l.allow_at("a", t));
62        assert!(!l.allow_at("a", t));
63        assert!(l.allow_at("b", t), "buckets are independent");
64        assert!(l.allow_at("a", t + Duration::from_secs(30)));
65    }
66}