Skip to main content

fastauth_core/
rate_limit.rs

1//! GCRA rate limiting: one timestamp per key, in sharded in-memory maps.
2
3use std::collections::HashMap;
4use std::hash::{BuildHasher, RandomState};
5use std::sync::Mutex;
6use std::time::{Duration as StdDuration, Instant};
7
8use time::Duration;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct Limit {
12    pub period: Duration,
13    pub max: u32,
14}
15
16impl Limit {
17    /// `max` requests per `period`, allowing bursts of `max`.
18    pub fn per(period: Duration, max: u32) -> Self {
19        assert!(max > 0, "a rate limit allows at least one request");
20        Self { period, max }
21    }
22
23    fn interval(&self) -> StdDuration {
24        StdDuration::try_from(self.period).unwrap_or(StdDuration::ZERO) / self.max
25    }
26
27    fn burst(&self) -> StdDuration {
28        StdDuration::try_from(self.period).unwrap_or(StdDuration::ZERO)
29    }
30}
31
32/// A path pattern: exact (`/sign-in/email`) or prefix (`/sign-in/*`).
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct Rule {
35    pub pattern: String,
36    pub limit: Limit,
37}
38
39impl Rule {
40    fn matches(&self, path: &str) -> bool {
41        match self.pattern.strip_suffix('*') {
42            Some(prefix) => path.starts_with(prefix),
43            None => self.pattern == path,
44        }
45    }
46}
47
48#[derive(Clone, Debug)]
49pub struct RateLimit {
50    pub(crate) enabled: bool,
51    pub(crate) default: Limit,
52    /// Checked in order; the first match wins. App rules come first, then plugin rules, then core.
53    pub(crate) rules: Vec<Rule>,
54}
55
56impl Default for RateLimit {
57    fn default() -> Self {
58        Self {
59            enabled: true,
60            default: Limit::per(Duration::seconds(10), 100),
61            rules: Vec::new(),
62        }
63    }
64}
65
66impl RateLimit {
67    pub fn disabled() -> Self {
68        Self {
69            enabled: false,
70            ..Self::default()
71        }
72    }
73
74    pub fn default_limit(mut self, limit: Limit) -> Self {
75        self.default = limit;
76        self
77    }
78
79    pub fn rule(mut self, pattern: impl Into<String>, limit: Limit) -> Self {
80        self.rules.push(Rule {
81            pattern: pattern.into(),
82            limit,
83        });
84        self
85    }
86
87    pub(crate) fn core_rules() -> Vec<Rule> {
88        let strict = Limit::per(Duration::seconds(10), 3);
89        [
90            "/sign-in/*",
91            "/sign-up/*",
92            "/request-password-reset",
93            "/forget-password",
94            "/send-verification-email",
95        ]
96        .into_iter()
97        .map(|p| Rule {
98            pattern: p.into(),
99            limit: strict,
100        })
101        .collect()
102    }
103
104    fn limit_for(&self, path: &str) -> (&str, Limit) {
105        self.rules
106            .iter()
107            .find(|r| r.matches(path))
108            .map_or(("*", self.default), |r| (r.pattern.as_str(), r.limit))
109    }
110}
111
112const SHARDS: usize = 16;
113
114pub(crate) struct RateLimiter {
115    config: RateLimit,
116    shards: Vec<Mutex<HashMap<String, Instant>>>,
117    hasher: RandomState,
118}
119
120impl RateLimiter {
121    pub(crate) fn new(config: RateLimit) -> Self {
122        Self {
123            config,
124            shards: (0..SHARDS).map(|_| Mutex::default()).collect(),
125            hasher: RandomState::new(),
126        }
127    }
128
129    /// Whether the request may proceed. `path` is relative to the base path.
130    pub(crate) fn check(&self, client: &str, path: &str) -> bool {
131        self.check_at(client, path, Instant::now())
132    }
133
134    fn check_at(&self, client: &str, path: &str, now: Instant) -> bool {
135        if !self.config.enabled {
136            return true;
137        }
138        let (rule, limit) = self.config.limit_for(path);
139        let key = format!(
140            "{client}|{rule}|{}",
141            if rule.ends_with('*') { "" } else { path }
142        );
143        let shard = &self.shards[self.hasher.hash_one(&key) as usize % SHARDS];
144        let mut map = shard.lock().unwrap();
145        if map.len() > 50_000 {
146            map.retain(|_, tat| *tat > now);
147        }
148        let interval = limit.interval();
149        let tat = map.get(&key).copied().unwrap_or(now).max(now);
150        let next = tat + interval;
151        if next > now + limit.burst() {
152            return false;
153        }
154        map.insert(key, next);
155        true
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn allows_burst_then_limits() {
165        let limiter = RateLimiter::new(
166            RateLimit::default().rule("/sign-in/*", Limit::per(Duration::seconds(10), 3)),
167        );
168        let now = Instant::now();
169        assert!((0..3).all(|_| limiter.check_at("1.2.3.4", "/sign-in/email", now)));
170        assert!(!limiter.check_at("1.2.3.4", "/sign-in/email", now));
171        assert!(
172            limiter.check_at("5.6.7.8", "/sign-in/email", now),
173            "other clients are unaffected"
174        );
175        assert!(limiter.check_at("1.2.3.4", "/sign-in/email", now + StdDuration::from_secs(4)));
176    }
177}