1use std::collections::HashMap;
4use std::hash::{BuildHasher, RandomState};
5use std::net::{IpAddr, Ipv6Addr};
6use std::sync::Mutex;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::time::{Duration as StdDuration, Instant};
9
10use time::Duration;
11
12use crate::config::ClientIp;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub struct Limit {
16 pub period: Duration,
17 pub max: u32,
18}
19
20impl Limit {
21 pub fn per(period: Duration, max: u32) -> Self {
23 assert!(max > 0, "a rate limit allows at least one request");
24 Self { period, max }
25 }
26
27 fn interval(&self) -> StdDuration {
28 StdDuration::try_from(self.period).unwrap_or(StdDuration::ZERO) / self.max
29 }
30
31 fn burst(&self) -> StdDuration {
32 StdDuration::try_from(self.period).unwrap_or(StdDuration::ZERO)
33 }
34}
35
36#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct Rule {
39 pub pattern: String,
40 pub limit: Limit,
41}
42
43impl Rule {
44 fn matches(&self, path: &str) -> bool {
45 match self.pattern.strip_suffix('*') {
46 Some(prefix) => path.starts_with(prefix),
47 None => self.pattern == path,
48 }
49 }
50}
51
52#[derive(Clone, Debug)]
53pub struct RateLimit {
54 pub(crate) enabled: bool,
55 pub(crate) default: Limit,
56 pub(crate) rules: Vec<Rule>,
58 pub(crate) account: Option<Limit>,
59 pub(crate) ipv6_prefix: u8,
60 pub(crate) max_keys: usize,
61}
62
63impl Default for RateLimit {
64 fn default() -> Self {
65 Self {
66 enabled: true,
67 default: Limit::per(Duration::seconds(10), 100),
68 rules: Vec::new(),
69 account: Some(Limit::per(Duration::minutes(10), 30)),
70 ipv6_prefix: 64,
71 max_keys: 100_000,
72 }
73 }
74}
75
76impl RateLimit {
77 pub fn disabled() -> Self {
78 Self {
79 enabled: false,
80 ..Self::default()
81 }
82 }
83
84 pub fn default_limit(mut self, limit: Limit) -> Self {
85 self.default = limit;
86 self
87 }
88
89 pub fn rule(mut self, pattern: impl Into<String>, limit: Limit) -> Self {
90 self.rules.push(Rule {
91 pattern: pattern.into(),
92 limit,
93 });
94 self
95 }
96
97 pub fn account_limit(mut self, limit: Option<Limit>) -> Self {
102 self.account = limit;
103 self
104 }
105
106 pub fn ipv6_prefix(mut self, bits: u8) -> Self {
110 assert!(bits <= 128, "an IPv6 prefix is at most 128 bits");
111 self.ipv6_prefix = bits;
112 self
113 }
114
115 pub fn max_keys(mut self, max: usize) -> Self {
118 assert!(max > 0, "the rate limiter keeps at least one key");
119 self.max_keys = max;
120 self
121 }
122
123 pub(crate) fn core_rules() -> Vec<Rule> {
124 let strict = Limit::per(Duration::seconds(10), 3);
125 [
126 "/sign-in/*",
127 "/sign-up/*",
128 "/request-password-reset",
129 "/forget-password",
130 "/send-verification-email",
131 "/change-password",
132 ]
133 .into_iter()
134 .map(|p| Rule {
135 pattern: p.into(),
136 limit: strict,
137 })
138 .collect()
139 }
140
141 fn limit_for(&self, path: &str) -> (&str, Limit) {
142 self.rules
143 .iter()
144 .find(|r| r.matches(path))
145 .map_or(("*", self.default), |r| (r.pattern.as_str(), r.limit))
146 }
147}
148
149const SHARDS: usize = 16;
150
151const NO_CLIENT_IP: &str = "no-client-ip";
153
154const PRUNE_EVERY: u32 = 1024;
156
157fn accounts_in(body: &[u8]) -> Vec<String> {
159 #[derive(serde::Deserialize)]
160 struct Named {
161 email: Option<String>,
162 username: Option<String>,
163 }
164 let Ok(named) = serde_json::from_slice::<Named>(body) else {
165 return Vec::new();
166 };
167 [named.email, named.username]
168 .into_iter()
169 .flatten()
170 .map(|account| account.trim().to_lowercase())
171 .collect()
172}
173
174#[derive(Default)]
175struct Shard {
176 keys: HashMap<String, Instant>,
177 inserts: u32,
178}
179
180pub(crate) struct RateLimiter {
181 config: RateLimit,
182 shards: Vec<Mutex<Shard>>,
183 hasher: RandomState,
184 warned_no_ip: AtomicBool,
185 production: bool,
186}
187
188impl RateLimiter {
189 pub(crate) fn new(config: RateLimit, production: bool) -> Self {
191 Self {
192 config,
193 shards: (0..SHARDS).map(|_| Mutex::default()).collect(),
194 hasher: RandomState::new(),
195 warned_no_ip: AtomicBool::new(false),
196 production,
197 }
198 }
199
200 pub(crate) fn check(&self, ip: IpAddr, path: &str, body: &[u8]) -> bool {
202 self.check_at(&self.client_key(ip), path, body, Instant::now())
203 }
204
205 fn client_key(&self, ip: IpAddr) -> String {
207 match ip.to_canonical() {
208 IpAddr::V4(v4) => v4.to_string(),
209 IpAddr::V6(v6) => {
210 let prefix = self.config.ipv6_prefix;
211 let mask = u128::MAX.checked_shl(128 - u32::from(prefix)).unwrap_or(0);
212 format!("{}/{prefix}", Ipv6Addr::from(u128::from(v6) & mask))
213 }
214 }
215 }
216
217 fn account_key(&self, account: &str) -> String {
219 format!("{:016x}", self.hasher.hash_one(account))
220 }
221
222 pub(crate) fn check_without_ip(&self, source: &ClientIp, path: &str, body: &[u8]) -> bool {
227 if !self.config.enabled {
228 return true;
229 }
230 if !self.warned_no_ip.swap(true, Ordering::Relaxed) {
231 let header = match source {
232 ClientIp::Socket => None,
233 ClientIp::Header(header) | ClientIp::TrustedProxies { header, .. } => {
234 Some(header.as_str())
235 }
236 };
237 let message = match header {
238 None => {
239 "fastauth can't tell clients apart: requests carry no client socket address, \
240 so rate limits are per account or shared by everyone. In axum, serve with \
241 into_make_service_with_connect_info::<SocketAddr>(); behind a proxy, set \
242 .client_ip(ClientIp::Header(..)) or ClientIp::TrustedProxies"
243 }
244 Some(_) => {
245 "fastauth got a request without a valid client IP in its client IP header, \
246 so rate limits are per account or shared by everyone. Check that the proxy \
247 sets the header and that ClientIp matches the proxy chain"
248 }
249 };
250 if self.production {
251 tracing::error!(header, "{message}");
252 } else {
253 tracing::warn!(header, "{message}");
254 }
255 }
256 let now = Instant::now();
257 let accounts = accounts_in(body);
258 if accounts.is_empty() {
259 return self.take_rule(NO_CLIENT_IP, path, now);
260 }
261 accounts.iter().all(|account| {
262 let client = format!("{NO_CLIENT_IP}:{}", self.account_key(account));
263 self.take_rule(&client, path, now)
264 })
265 }
266
267 fn check_at(&self, client: &str, path: &str, body: &[u8], now: Instant) -> bool {
270 if !self.config.enabled {
271 return true;
272 }
273 if !self.take_rule(client, path, now) {
274 return false;
275 }
276 let (rule, _) = self.config.limit_for(path);
277 let Some(limit) = self.config.account.filter(|_| rule != "*") else {
278 return true;
279 };
280 accounts_in(body).iter().all(|account| {
281 let key = format!("account:{}|{rule}", self.account_key(account));
282 self.take(key, limit, now)
283 })
284 }
285
286 fn take_rule(&self, client: &str, path: &str, now: Instant) -> bool {
287 let (rule, limit) = self.config.limit_for(path);
288 let key = format!(
289 "{client}|{rule}|{}",
290 if rule.ends_with('*') { "" } else { path }
291 );
292 self.take(key, limit, now)
293 }
294
295 fn take(&self, key: String, limit: Limit, now: Instant) -> bool {
297 let shard = &self.shards[self.hasher.hash_one(&key) as usize % SHARDS];
298 let mut shard = shard.lock().unwrap();
299 let cap = (self.config.max_keys / SHARDS).max(1);
300 shard.inserts = shard.inserts.wrapping_add(1);
301 if shard.inserts.is_multiple_of(PRUNE_EVERY)
302 || (shard.keys.len() >= cap && !shard.keys.contains_key(&key))
303 {
304 shard.keys.retain(|_, tat| *tat > now);
305 }
306 if shard.keys.len() >= cap && !shard.keys.contains_key(&key) {
307 let mut tats: Vec<Instant> = shard.keys.values().copied().collect();
308 let middle = tats.len() / 2;
309 let cutoff = *tats.select_nth_unstable(middle).1;
310 shard.keys.retain(|_, tat| *tat > cutoff);
311 }
312 let tat = shard.keys.get(&key).copied().unwrap_or(now).max(now);
313 let next = tat + limit.interval();
314 if next > now + limit.burst() {
315 return false;
316 }
317 shard.keys.insert(key, next);
318 true
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 #[test]
327 fn allows_burst_then_limits() {
328 let limiter = RateLimiter::new(
329 RateLimit::default().rule("/sign-in/*", Limit::per(Duration::seconds(10), 3)),
330 false,
331 );
332 let now = Instant::now();
333 assert!((0..3).all(|_| limiter.check_at("1.2.3.4", "/sign-in/email", b"", now)));
334 assert!(!limiter.check_at("1.2.3.4", "/sign-in/email", b"", now));
335 assert!(
336 limiter.check_at("5.6.7.8", "/sign-in/email", b"", now),
337 "other clients are unaffected"
338 );
339 assert!(limiter.check_at(
340 "1.2.3.4",
341 "/sign-in/email",
342 b"",
343 now + StdDuration::from_secs(4)
344 ));
345 }
346
347 #[test]
348 fn without_a_client_ip_limits_apply_per_named_account() {
349 let limiter = RateLimiter::new(
350 RateLimit::default().rule("/sign-in/*", Limit::per(Duration::seconds(10), 3)),
351 false,
352 );
353 let source = ClientIp::Socket;
354 let attacker = br#"{"email":"someone@acme.dk","password":"x"}"#;
355 assert!((0..3).all(|_| limiter.check_without_ip(&source, "/sign-in/email", attacker)));
356 assert!(!limiter.check_without_ip(&source, "/sign-in/email", attacker));
357 assert!(
358 !limiter.check_without_ip(
359 &source,
360 "/sign-in/email",
361 br#"{"email":" SOMEONE@acme.dk "}"#
362 ),
363 "the account key is normalized"
364 );
365 assert!(limiter.check_without_ip(
366 &source,
367 "/sign-in/email",
368 br#"{"email":"victim@acme.dk"}"#
369 ));
370 assert!(limiter.check_without_ip(&source, "/sign-in/username", br#"{"username":"ada"}"#));
371 assert!((0..3).all(|_| limiter.check_without_ip(&source, "/sign-in/x", b"{}")));
372 assert!(
373 !limiter.check_without_ip(&source, "/sign-in/x", b""),
374 "the rest share a bucket"
375 );
376 }
377
378 #[test]
379 fn ipv6_clients_share_their_prefix() {
380 let limiter = RateLimiter::new(RateLimit::default(), false);
381 let a: IpAddr = "2001:db8:1:2::1".parse().unwrap();
382 let b: IpAddr = "2001:db8:1:2:ffff::9".parse().unwrap();
383 let other: IpAddr = "2001:db8:1:3::1".parse().unwrap();
384 assert_eq!(limiter.client_key(a), "2001:db8:1:2::/64");
385 assert_eq!(limiter.client_key(a), limiter.client_key(b));
386 assert_ne!(limiter.client_key(a), limiter.client_key(other));
387 let mapped: IpAddr = "::ffff:203.0.113.9".parse().unwrap();
388 assert_eq!(limiter.client_key(mapped), "203.0.113.9");
389 let full = RateLimiter::new(RateLimit::default().ipv6_prefix(128), false);
390 assert_ne!(full.client_key(a), full.client_key(b));
391 let all = RateLimiter::new(RateLimit::default().ipv6_prefix(0), false);
392 assert_eq!(all.client_key(a), "::/0");
393 }
394
395 #[test]
396 fn keys_stay_under_max_keys() {
397 let limiter = RateLimiter::new(RateLimit::default().max_keys(SHARDS * 10), false);
398 let now = Instant::now();
399 for n in 0..5_000 {
400 assert!(limiter.check_at(&format!("10.0.{}.{}", n / 256, n % 256), "/x", b"", now));
401 }
402 let kept: usize = limiter
403 .shards
404 .iter()
405 .map(|s| s.lock().unwrap().keys.len())
406 .sum();
407 assert!(kept <= SHARDS * 10, "{kept} keys kept");
408 }
409
410 #[test]
411 fn account_limit_spans_clients_on_ruled_routes() {
412 let limiter = RateLimiter::new(
413 RateLimit::default()
414 .rule("/sign-in/*", Limit::per(Duration::seconds(10), 3))
415 .account_limit(Some(Limit::per(Duration::minutes(10), 5))),
416 false,
417 );
418 let now = Instant::now();
419 let body = br#"{"email":"ada@acme.dk"}"#;
420 let allowed = (0..10)
421 .filter(|n| limiter.check_at(&format!("10.0.0.{n}"), "/sign-in/email", body, now))
422 .count();
423 assert_eq!(allowed, 5);
424 assert!(
425 (0..10).all(|n| limiter.check_at(&format!("10.0.1.{n}"), "/other", body, now)),
426 "routes on the default limit have no account limit"
427 );
428 }
429}