1use std::collections::HashMap;
4use std::hash::{BuildHasher, RandomState};
5use std::sync::Mutex;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::time::{Duration as StdDuration, Instant};
8
9use time::Duration;
10
11use crate::config::ClientIp;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct Limit {
15 pub period: Duration,
16 pub max: u32,
17}
18
19impl Limit {
20 pub fn per(period: Duration, max: u32) -> Self {
22 assert!(max > 0, "a rate limit allows at least one request");
23 Self { period, max }
24 }
25
26 fn interval(&self) -> StdDuration {
27 StdDuration::try_from(self.period).unwrap_or(StdDuration::ZERO) / self.max
28 }
29
30 fn burst(&self) -> StdDuration {
31 StdDuration::try_from(self.period).unwrap_or(StdDuration::ZERO)
32 }
33}
34
35#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct Rule {
38 pub pattern: String,
39 pub limit: Limit,
40}
41
42impl Rule {
43 fn matches(&self, path: &str) -> bool {
44 match self.pattern.strip_suffix('*') {
45 Some(prefix) => path.starts_with(prefix),
46 None => self.pattern == path,
47 }
48 }
49}
50
51#[derive(Clone, Debug)]
52pub struct RateLimit {
53 pub(crate) enabled: bool,
54 pub(crate) default: Limit,
55 pub(crate) rules: Vec<Rule>,
57}
58
59impl Default for RateLimit {
60 fn default() -> Self {
61 Self {
62 enabled: true,
63 default: Limit::per(Duration::seconds(10), 100),
64 rules: Vec::new(),
65 }
66 }
67}
68
69impl RateLimit {
70 pub fn disabled() -> Self {
71 Self {
72 enabled: false,
73 ..Self::default()
74 }
75 }
76
77 pub fn default_limit(mut self, limit: Limit) -> Self {
78 self.default = limit;
79 self
80 }
81
82 pub fn rule(mut self, pattern: impl Into<String>, limit: Limit) -> Self {
83 self.rules.push(Rule {
84 pattern: pattern.into(),
85 limit,
86 });
87 self
88 }
89
90 pub(crate) fn core_rules() -> Vec<Rule> {
91 let strict = Limit::per(Duration::seconds(10), 3);
92 [
93 "/sign-in/*",
94 "/sign-up/*",
95 "/request-password-reset",
96 "/forget-password",
97 "/send-verification-email",
98 "/change-password",
99 ]
100 .into_iter()
101 .map(|p| Rule {
102 pattern: p.into(),
103 limit: strict,
104 })
105 .collect()
106 }
107
108 fn limit_for(&self, path: &str) -> (&str, Limit) {
109 self.rules
110 .iter()
111 .find(|r| r.matches(path))
112 .map_or(("*", self.default), |r| (r.pattern.as_str(), r.limit))
113 }
114}
115
116const SHARDS: usize = 16;
117
118const NO_CLIENT_IP: &str = "no-client-ip";
120
121fn account_in(body: &[u8]) -> Option<String> {
123 #[derive(serde::Deserialize)]
124 struct Named {
125 email: Option<String>,
126 username: Option<String>,
127 }
128 let named: Named = serde_json::from_slice(body).ok()?;
129 let account = named.email.or(named.username)?;
130 Some(account.trim().to_lowercase())
131}
132
133pub(crate) struct RateLimiter {
134 config: RateLimit,
135 shards: Vec<Mutex<HashMap<String, Instant>>>,
136 hasher: RandomState,
137 warned_no_ip: AtomicBool,
138}
139
140impl RateLimiter {
141 pub(crate) fn new(config: RateLimit) -> Self {
142 Self {
143 config,
144 shards: (0..SHARDS).map(|_| Mutex::default()).collect(),
145 hasher: RandomState::new(),
146 warned_no_ip: AtomicBool::new(false),
147 }
148 }
149
150 pub(crate) fn check(&self, client: &str, path: &str) -> bool {
152 self.check_at(client, path, Instant::now())
153 }
154
155 pub(crate) fn check_without_ip(&self, source: &ClientIp, path: &str, body: &[u8]) -> bool {
160 if !self.config.enabled {
161 return true;
162 }
163 if !self.warned_no_ip.swap(true, Ordering::Relaxed) {
164 match source {
165 ClientIp::Socket => tracing::warn!(
166 "fastauth can't tell clients apart: requests carry no client socket address, \
167 so rate limits are per account or shared by everyone. In axum, serve with \
168 into_make_service_with_connect_info::<SocketAddr>(); behind a proxy, set \
169 .client_ip(ClientIp::Header(..)) or ClientIp::TrustedProxies"
170 ),
171 ClientIp::Header(header) | ClientIp::TrustedProxies { header, .. } => {
172 tracing::warn!(
173 header = header.as_str(),
174 "fastauth got a request without a valid client IP in its client IP \
175 header, so rate limits are per account or shared by everyone. Check \
176 that the proxy sets the header and that ClientIp matches the proxy chain"
177 )
178 }
179 }
180 }
181 match account_in(body) {
182 Some(account) => self.check(&format!("{NO_CLIENT_IP}:{account}"), path),
183 None => self.check(NO_CLIENT_IP, path),
184 }
185 }
186
187 fn check_at(&self, client: &str, path: &str, now: Instant) -> bool {
188 if !self.config.enabled {
189 return true;
190 }
191 let (rule, limit) = self.config.limit_for(path);
192 let key = format!(
193 "{client}|{rule}|{}",
194 if rule.ends_with('*') { "" } else { path }
195 );
196 let shard = &self.shards[self.hasher.hash_one(&key) as usize % SHARDS];
197 let mut map = shard.lock().unwrap();
198 if map.len() > 50_000 {
199 map.retain(|_, tat| *tat > now);
200 }
201 let interval = limit.interval();
202 let tat = map.get(&key).copied().unwrap_or(now).max(now);
203 let next = tat + interval;
204 if next > now + limit.burst() {
205 return false;
206 }
207 map.insert(key, next);
208 true
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 #[test]
217 fn allows_burst_then_limits() {
218 let limiter = RateLimiter::new(
219 RateLimit::default().rule("/sign-in/*", Limit::per(Duration::seconds(10), 3)),
220 );
221 let now = Instant::now();
222 assert!((0..3).all(|_| limiter.check_at("1.2.3.4", "/sign-in/email", now)));
223 assert!(!limiter.check_at("1.2.3.4", "/sign-in/email", now));
224 assert!(
225 limiter.check_at("5.6.7.8", "/sign-in/email", now),
226 "other clients are unaffected"
227 );
228 assert!(limiter.check_at("1.2.3.4", "/sign-in/email", now + StdDuration::from_secs(4)));
229 }
230
231 #[test]
232 fn without_a_client_ip_limits_apply_per_named_account() {
233 let limiter = RateLimiter::new(
234 RateLimit::default().rule("/sign-in/*", Limit::per(Duration::seconds(10), 3)),
235 );
236 let source = ClientIp::Socket;
237 let attacker = br#"{"email":"someone@acme.dk","password":"x"}"#;
238 assert!((0..3).all(|_| limiter.check_without_ip(&source, "/sign-in/email", attacker)));
239 assert!(!limiter.check_without_ip(&source, "/sign-in/email", attacker));
240 assert!(
241 !limiter.check_without_ip(
242 &source,
243 "/sign-in/email",
244 br#"{"email":" SOMEONE@acme.dk "}"#
245 ),
246 "the account key is normalized"
247 );
248 assert!(limiter.check_without_ip(
249 &source,
250 "/sign-in/email",
251 br#"{"email":"victim@acme.dk"}"#
252 ));
253 assert!(limiter.check_without_ip(&source, "/sign-in/username", br#"{"username":"ada"}"#));
254 assert!((0..3).all(|_| limiter.check_without_ip(&source, "/sign-in/x", b"{}")));
255 assert!(
256 !limiter.check_without_ip(&source, "/sign-in/x", b""),
257 "the rest share a bucket"
258 );
259 }
260}