Skip to main content

fastauth_core/
rate_limit.rs

1//! Rate limiting: GCRA in sharded in-memory maps, or fixed windows in secondary storage.
2
3use 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 hmac::{Hmac, KeyInit, Mac};
11use sha2::Sha256;
12use time::Duration;
13use zeroize::Zeroizing;
14
15use crate::config::ClientIp;
16use crate::storage::{GuardedStorage, StorageError};
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct Limit {
20    pub period: Duration,
21    pub max: u32,
22}
23
24impl Limit {
25    /// `max` requests per `period`, allowing bursts of `max`.
26    pub fn per(period: Duration, max: u32) -> Self {
27        assert!(max > 0, "a rate limit allows at least one request");
28        Self { period, max }
29    }
30
31    fn interval(&self) -> StdDuration {
32        StdDuration::try_from(self.period).unwrap_or(StdDuration::ZERO) / self.max
33    }
34
35    fn burst(&self) -> StdDuration {
36        StdDuration::try_from(self.period).unwrap_or(StdDuration::ZERO)
37    }
38}
39
40/// A path pattern: exact (`/sign-in/email`) or prefix (`/sign-in/*`).
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct Rule {
43    pub pattern: String,
44    pub limit: Limit,
45}
46
47impl Rule {
48    fn matches(&self, path: &str) -> bool {
49        match self.pattern.strip_suffix('*') {
50            Some(prefix) => path.starts_with(prefix),
51            None => self.pattern == path,
52        }
53    }
54}
55
56#[derive(Clone, Debug)]
57pub struct RateLimit {
58    pub(crate) enabled: bool,
59    pub(crate) default: Limit,
60    /// Checked in order; the first match wins. App rules come first, then plugin rules, then core.
61    pub(crate) rules: Vec<Rule>,
62    pub(crate) account: Option<Limit>,
63    pub(crate) ipv6_prefix: u8,
64    pub(crate) max_keys: usize,
65}
66
67impl Default for RateLimit {
68    fn default() -> Self {
69        Self {
70            enabled: true,
71            default: Limit::per(Duration::seconds(10), 100),
72            rules: Vec::new(),
73            account: Some(Limit::per(Duration::minutes(10), 30)),
74            ipv6_prefix: 64,
75            max_keys: 100_000,
76        }
77    }
78}
79
80impl RateLimit {
81    pub fn disabled() -> Self {
82        Self {
83            enabled: false,
84            ..Self::default()
85        }
86    }
87
88    pub fn default_limit(mut self, limit: Limit) -> Self {
89        self.default = limit;
90        self
91    }
92
93    pub fn rule(mut self, pattern: impl Into<String>, limit: Limit) -> Self {
94        self.rules.push(Rule {
95            pattern: pattern.into(),
96            limit,
97        });
98        self
99    }
100
101    /// A second limit on routes with a rule of their own (sign-in, sign-up, password reset,
102    /// plugin routes that send mail or check codes), kept per account the JSON body names
103    /// (`email` or `username`) whatever the client IP. It stops guesses at one account
104    /// spread over many addresses. Default: 30 requests per 10 minutes; `None` turns it off.
105    pub fn account_limit(mut self, limit: Option<Limit>) -> Self {
106        self.account = limit;
107        self
108    }
109
110    /// IPv6 clients share one bucket per network prefix of this many bits (default 64, as in
111    /// Better Auth), because one subscriber or cloud VM holds a whole /64. 128 keeps every
112    /// address apart.
113    pub fn ipv6_prefix(mut self, bits: u8) -> Self {
114        assert!(bits <= 128, "an IPv6 prefix is at most 128 bits");
115        self.ipv6_prefix = bits;
116        self
117    }
118
119    /// The most keys the limiter keeps in memory (default 100,000). When it is full, expired
120    /// keys go first, then the half closest to expiry.
121    pub fn max_keys(mut self, max: usize) -> Self {
122        assert!(max > 0, "the rate limiter keeps at least one key");
123        self.max_keys = max;
124        self
125    }
126
127    pub(crate) fn core_rules() -> Vec<Rule> {
128        let strict = Limit::per(Duration::seconds(10), 3);
129        [
130            "/sign-in/*",
131            "/sign-up/*",
132            "/request-password-reset",
133            "/forget-password",
134            "/send-verification-email",
135            "/change-password",
136        ]
137        .into_iter()
138        .map(|p| Rule {
139            pattern: p.into(),
140            limit: strict,
141        })
142        .collect()
143    }
144
145    fn limit_for(&self, path: &str) -> (&str, Limit) {
146        self.rules
147            .iter()
148            .find(|r| r.matches(path))
149            .map_or(("*", self.default), |r| (r.pattern.as_str(), r.limit))
150    }
151}
152
153const SHARDS: usize = 16;
154
155/// The key prefix for requests without a client IP. Not an IP, so it can't collide with one.
156const NO_CLIENT_IP: &str = "no-client-ip";
157
158/// Every so many inserts, a shard drops its expired keys.
159const PRUNE_EVERY: u32 = 1024;
160
161/// The accounts a JSON body names, lowercased: its `email` and its `username`.
162fn accounts_in(body: &[u8]) -> Vec<String> {
163    #[derive(serde::Deserialize)]
164    struct Named {
165        email: Option<String>,
166        username: Option<String>,
167    }
168    let Ok(named) = serde_json::from_slice::<Named>(body) else {
169        return Vec::new();
170    };
171    [named.email, named.username]
172        .into_iter()
173        .flatten()
174        .map(|account| account.trim().to_lowercase())
175        .collect()
176}
177
178#[derive(Default)]
179struct Shard {
180    keys: HashMap<String, Instant>,
181    inserts: u32,
182}
183
184pub(crate) struct RateLimiter {
185    config: RateLimit,
186    shards: Vec<Mutex<Shard>>,
187    hasher: RandomState,
188    /// Keys account buckets, so they name no email and agree across instances that share
189    /// the secret.
190    account_key: Zeroizing<[u8; 32]>,
191    /// Where counters live when the app configured secondary storage; in `shards` otherwise.
192    storage: Option<GuardedStorage>,
193    last_storage_error: Mutex<Option<Instant>>,
194    warned_no_ip: AtomicBool,
195    production: bool,
196}
197
198/// How often a failing secondary storage is logged.
199const STORAGE_ERROR_LOG_EVERY: StdDuration = StdDuration::from_secs(60);
200
201impl RateLimiter {
202    /// `production` logs a request without a client IP as an error rather than a warning.
203    /// With `storage`, counters live there and every instance sharing it shares the limits.
204    pub(crate) fn new(
205        config: RateLimit,
206        production: bool,
207        account_key: Zeroizing<[u8; 32]>,
208        storage: Option<GuardedStorage>,
209    ) -> Self {
210        Self {
211            config,
212            shards: (0..SHARDS).map(|_| Mutex::default()).collect(),
213            hasher: RandomState::new(),
214            account_key,
215            storage,
216            last_storage_error: Mutex::new(None),
217            warned_no_ip: AtomicBool::new(false),
218            production,
219        }
220    }
221
222    /// Whether a request from `ip` may proceed. `path` is relative to the base path.
223    pub(crate) async fn check(&self, ip: IpAddr, path: &str, body: &[u8]) -> bool {
224        if !self.config.enabled {
225            return true;
226        }
227        self.take_all(self.buckets(&self.client_key(ip), path, body))
228            .await
229    }
230
231    /// The bucket of a client address: the address for IPv4, its network prefix for IPv6.
232    fn client_key(&self, ip: IpAddr) -> String {
233        match ip.to_canonical() {
234            IpAddr::V4(v4) => v4.to_string(),
235            IpAddr::V6(v6) => {
236                let prefix = self.config.ipv6_prefix;
237                let mask = u128::MAX.checked_shl(128 - u32::from(prefix)).unwrap_or(0);
238                format!("{}/{prefix}", Ipv6Addr::from(u128::from(v6) & mask))
239            }
240        }
241    }
242
243    /// A fixed-size key for an account: a keyed hash, so a long `email` in a body costs no
244    /// memory and secondary storage never sees the address.
245    fn account_key(&self, account: &str) -> String {
246        let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(self.account_key.as_slice())
247            .expect("HMAC takes any key length");
248        mac.update(account.as_bytes());
249        mac.finalize().into_bytes()[..16]
250            .iter()
251            .map(|byte| format!("{byte:02x}"))
252            .collect()
253    }
254
255    /// Whether a request without a client IP may proceed. A JSON body naming an account
256    /// (`email` or `username`) is limited per account, so one client guessing passwords can't
257    /// throttle sign-in for everybody; other requests share one bucket, as in Better Auth.
258    /// The first such request is logged.
259    pub(crate) async fn check_without_ip(
260        &self,
261        source: &ClientIp,
262        path: &str,
263        body: &[u8],
264    ) -> bool {
265        if !self.config.enabled {
266            return true;
267        }
268        if !self.warned_no_ip.swap(true, Ordering::Relaxed) {
269            let header = match source {
270                ClientIp::Socket => None,
271                ClientIp::Header(header) | ClientIp::TrustedProxies { header, .. } => {
272                    Some(header.as_str())
273                }
274            };
275            let message = match header {
276                None => {
277                    "fastauth can't tell clients apart: requests carry no client socket address, \
278                     so rate limits are per account or shared by everyone. In axum, serve with \
279                     into_make_service_with_connect_info::<SocketAddr>(); behind a proxy, set \
280                     .client_ip(ClientIp::Header(..)) or ClientIp::TrustedProxies"
281                }
282                Some(_) => {
283                    "fastauth got a request without a valid client IP in its client IP header, \
284                     so rate limits are per account or shared by everyone. Check that the proxy \
285                     sets the header and that ClientIp matches the proxy chain"
286                }
287            };
288            if self.production {
289                tracing::error!(header, "{message}");
290            } else {
291                tracing::warn!(header, "{message}");
292            }
293        }
294        let accounts = accounts_in(body);
295        if accounts.is_empty() {
296            return self
297                .take_all(vec![self.rule_bucket(NO_CLIENT_IP, path)])
298                .await;
299        }
300        let buckets = accounts
301            .iter()
302            .map(|account| {
303                let client = format!("{NO_CLIENT_IP}:{}", self.account_key(account));
304                self.rule_bucket(&client, path)
305            })
306            .collect();
307        self.take_all(buckets).await
308    }
309
310    /// The buckets a request takes from, in order: the client's bucket for the route, then,
311    /// on routes with a rule of their own, the bucket of each account the body names.
312    fn buckets(&self, client: &str, path: &str, body: &[u8]) -> Vec<(String, Limit)> {
313        let mut buckets = vec![self.rule_bucket(client, path)];
314        let (rule, _) = self.config.limit_for(path);
315        if let Some(limit) = self.config.account.filter(|_| rule != "*") {
316            buckets.extend(accounts_in(body).iter().map(|account| {
317                let key = format!("account:{}|{rule}", self.account_key(account));
318                (key, limit)
319            }));
320        }
321        buckets
322    }
323
324    fn rule_bucket(&self, client: &str, path: &str) -> (String, Limit) {
325        let (rule, limit) = self.config.limit_for(path);
326        let key = format!(
327            "{client}|{rule}|{}",
328            if rule.ends_with('*') { "" } else { path }
329        );
330        (key, limit)
331    }
332
333    /// Takes one request from each bucket in turn and stops at the first that is empty. Once
334    /// the storage fails, the request's remaining buckets stay in memory, so a request waits
335    /// for at most one storage timeout.
336    async fn take_all(&self, buckets: Vec<(String, Limit)>) -> bool {
337        let now = Instant::now();
338        let mut storage = self.storage.as_ref();
339        for (key, limit) in buckets {
340            let allowed = match storage {
341                Some(shared) => match self.take_shared(shared, &key, limit).await {
342                    Some(allowed) => allowed,
343                    None => {
344                        storage = None;
345                        self.take(key, limit, now)
346                    }
347                },
348                None => self.take(key, limit, now),
349            };
350            if !allowed {
351                return false;
352            }
353        }
354        true
355    }
356
357    /// A fixed window in secondary storage: the first request in a window sets the counter's
358    /// TTL to the period, and the window allows `max` requests (Better Auth's
359    /// secondary-storage limiter). `None` when the storage failed, timed out or is skipped by
360    /// its circuit breaker: this instance's in-memory bucket decides then, so limits still
361    /// hold per instance.
362    async fn take_shared(&self, storage: &GuardedStorage, key: &str, limit: Limit) -> Option<bool> {
363        match storage
364            .increment(&format!("fastauth:rate-limit:{key}"), limit.burst())
365            .await
366        {
367            Ok(count) => Some(count <= u64::from(limit.max)),
368            Err(err) => {
369                self.log_storage_error(&err);
370                None
371            }
372        }
373    }
374
375    fn log_storage_error(&self, err: &StorageError) {
376        let mut last = self.last_storage_error.lock().unwrap();
377        if last.is_some_and(|at| at.elapsed() < STORAGE_ERROR_LOG_EVERY) {
378            return;
379        }
380        *last = Some(Instant::now());
381        tracing::error!(
382            error = %err,
383            "fastauth: secondary storage failed, so rate limits fall back to this instance's \
384             memory until it answers again"
385        );
386    }
387
388    /// The in-memory check of a request at `now`, for tests.
389    #[cfg(test)]
390    fn check_at(&self, client: &str, path: &str, body: &[u8], now: Instant) -> bool {
391        !self.config.enabled
392            || self
393                .buckets(client, path, body)
394                .into_iter()
395                .all(|(key, limit)| self.take(key, limit, now))
396    }
397
398    /// GCRA on one key. Each shard holds at most its share of `max_keys`.
399    fn take(&self, key: String, limit: Limit, now: Instant) -> bool {
400        let shard = &self.shards[self.hasher.hash_one(&key) as usize % SHARDS];
401        let mut shard = shard.lock().unwrap();
402        let cap = (self.config.max_keys / SHARDS).max(1);
403        shard.inserts = shard.inserts.wrapping_add(1);
404        if shard.inserts.is_multiple_of(PRUNE_EVERY)
405            || (shard.keys.len() >= cap && !shard.keys.contains_key(&key))
406        {
407            shard.keys.retain(|_, tat| *tat > now);
408        }
409        if shard.keys.len() >= cap && !shard.keys.contains_key(&key) {
410            let mut tats: Vec<Instant> = shard.keys.values().copied().collect();
411            let middle = tats.len() / 2;
412            let cutoff = *tats.select_nth_unstable(middle).1;
413            shard.keys.retain(|_, tat| *tat > cutoff);
414        }
415        let tat = shard.keys.get(&key).copied().unwrap_or(now).max(now);
416        let next = tat + limit.interval();
417        if next > now + limit.burst() {
418            return false;
419        }
420        shard.keys.insert(key, next);
421        true
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use std::sync::Arc;
428
429    use super::*;
430    use crate::storage::DEFAULT_STORAGE_TIMEOUT;
431    use crate::storage::fake::FakeStorage;
432
433    #[test]
434    fn allows_burst_then_limits() {
435        let limiter = in_memory(
436            RateLimit::default().rule("/sign-in/*", Limit::per(Duration::seconds(10), 3)),
437        );
438        let now = Instant::now();
439        assert!((0..3).all(|_| limiter.check_at("1.2.3.4", "/sign-in/email", b"", now)));
440        assert!(!limiter.check_at("1.2.3.4", "/sign-in/email", b"", now));
441        assert!(
442            limiter.check_at("5.6.7.8", "/sign-in/email", b"", now),
443            "other clients are unaffected"
444        );
445        assert!(limiter.check_at(
446            "1.2.3.4",
447            "/sign-in/email",
448            b"",
449            now + StdDuration::from_secs(4)
450        ));
451    }
452
453    #[tokio::test]
454    async fn without_a_client_ip_limits_apply_per_named_account() {
455        let limiter = in_memory(
456            RateLimit::default().rule("/sign-in/*", Limit::per(Duration::seconds(10), 3)),
457        );
458        let source = ClientIp::Socket;
459        let check =
460            async |path: &str, body: &[u8]| limiter.check_without_ip(&source, path, body).await;
461        let attacker = br#"{"email":"someone@acme.dk","password":"x"}"#;
462        for _ in 0..3 {
463            assert!(check("/sign-in/email", attacker).await);
464        }
465        assert!(!check("/sign-in/email", attacker).await);
466        assert!(
467            !check("/sign-in/email", br#"{"email":" SOMEONE@acme.dk "}"#).await,
468            "the account key is normalized"
469        );
470        assert!(check("/sign-in/email", br#"{"email":"victim@acme.dk"}"#).await);
471        assert!(check("/sign-in/username", br#"{"username":"ada"}"#).await);
472        for _ in 0..3 {
473            assert!(check("/sign-in/x", b"{}").await);
474        }
475        assert!(!check("/sign-in/x", b"").await, "the rest share a bucket");
476    }
477
478    #[test]
479    fn ipv6_clients_share_their_prefix() {
480        let limiter = in_memory(RateLimit::default());
481        let a: IpAddr = "2001:db8:1:2::1".parse().unwrap();
482        let b: IpAddr = "2001:db8:1:2:ffff::9".parse().unwrap();
483        let other: IpAddr = "2001:db8:1:3::1".parse().unwrap();
484        assert_eq!(limiter.client_key(a), "2001:db8:1:2::/64");
485        assert_eq!(limiter.client_key(a), limiter.client_key(b));
486        assert_ne!(limiter.client_key(a), limiter.client_key(other));
487        let mapped: IpAddr = "::ffff:203.0.113.9".parse().unwrap();
488        assert_eq!(limiter.client_key(mapped), "203.0.113.9");
489        let full = in_memory(RateLimit::default().ipv6_prefix(128));
490        assert_ne!(full.client_key(a), full.client_key(b));
491        let all = in_memory(RateLimit::default().ipv6_prefix(0));
492        assert_eq!(all.client_key(a), "::/0");
493    }
494
495    #[test]
496    fn keys_stay_under_max_keys() {
497        let limiter = in_memory(RateLimit::default().max_keys(SHARDS * 10));
498        let now = Instant::now();
499        for n in 0..5_000 {
500            assert!(limiter.check_at(&format!("10.0.{}.{}", n / 256, n % 256), "/x", b"", now));
501        }
502        let kept: usize = limiter
503            .shards
504            .iter()
505            .map(|s| s.lock().unwrap().keys.len())
506            .sum();
507        assert!(kept <= SHARDS * 10, "{kept} keys kept");
508    }
509
510    #[test]
511    fn account_limit_spans_clients_on_ruled_routes() {
512        let limiter = in_memory(
513            RateLimit::default()
514                .rule("/sign-in/*", Limit::per(Duration::seconds(10), 3))
515                .account_limit(Some(Limit::per(Duration::minutes(10), 5))),
516        );
517        let now = Instant::now();
518        let body = br#"{"email":"ada@acme.dk"}"#;
519        let allowed = (0..10)
520            .filter(|n| limiter.check_at(&format!("10.0.0.{n}"), "/sign-in/email", body, now))
521            .count();
522        assert_eq!(allowed, 5);
523        assert!(
524            (0..10).all(|n| limiter.check_at(&format!("10.0.1.{n}"), "/other", body, now)),
525            "routes on the default limit have no account limit"
526        );
527    }
528
529    fn in_memory(config: RateLimit) -> RateLimiter {
530        RateLimiter::new(config, false, Zeroizing::new([7; 32]), None)
531    }
532
533    fn shared(config: RateLimit, storage: &FakeStorage) -> RateLimiter {
534        guarded(
535            config,
536            GuardedStorage::new(Arc::new(storage.clone()), DEFAULT_STORAGE_TIMEOUT),
537        )
538    }
539
540    fn guarded(config: RateLimit, storage: GuardedStorage) -> RateLimiter {
541        RateLimiter::new(config, false, Zeroizing::new([7; 32]), Some(storage))
542    }
543
544    fn sign_in_rule() -> RateLimit {
545        RateLimit::default().rule("/sign-in/*", Limit::per(Duration::seconds(10), 3))
546    }
547
548    #[tokio::test]
549    async fn instances_sharing_storage_share_limits() {
550        let storage = FakeStorage::default();
551        let a = shared(sign_in_rule(), &storage);
552        let b = shared(sign_in_rule(), &storage);
553        let ip: IpAddr = "203.0.113.7".parse().unwrap();
554        assert!(a.check(ip, "/sign-in/email", b"").await);
555        assert!(b.check(ip, "/sign-in/email", b"").await);
556        assert!(a.check(ip, "/sign-in/email", b"").await);
557        assert!(
558            !b.check(ip, "/sign-in/email", b"").await,
559            "the fourth request is refused, whichever instance gets it"
560        );
561        assert!(!a.check(ip, "/sign-in/email", b"").await);
562        assert!(
563            a.check("203.0.113.8".parse().unwrap(), "/sign-in/email", b"")
564                .await,
565            "other clients are unaffected"
566        );
567
568        let alone = [in_memory(sign_in_rule()), in_memory(sign_in_rule())];
569        let mut allowed = 0;
570        for n in 0..8 {
571            allowed += usize::from(alone[n % 2].check(ip, "/sign-in/email", b"").await);
572        }
573        assert_eq!(
574            allowed, 6,
575            "without shared storage, each instance allows the limit"
576        );
577    }
578
579    #[tokio::test]
580    async fn shared_windows_reset_after_the_period() {
581        let storage = FakeStorage::default();
582        let config =
583            RateLimit::default().rule("/sign-in/*", Limit::per(Duration::milliseconds(300), 2));
584        let limiter = shared(config, &storage);
585        let ip: IpAddr = "203.0.113.7".parse().unwrap();
586        assert!(limiter.check(ip, "/sign-in/email", b"").await);
587        assert!(limiter.check(ip, "/sign-in/email", b"").await);
588        assert!(!limiter.check(ip, "/sign-in/email", b"").await);
589        tokio::time::sleep(StdDuration::from_millis(400)).await;
590        assert!(limiter.check(ip, "/sign-in/email", b"").await);
591    }
592
593    #[tokio::test]
594    async fn account_limits_are_shared_and_name_no_email() {
595        let storage = FakeStorage::default();
596        let config = sign_in_rule().account_limit(Some(Limit::per(Duration::minutes(10), 5)));
597        let instances = [shared(config.clone(), &storage), shared(config, &storage)];
598        let body = br#"{"email":"ada@acme.dk"}"#;
599        let mut allowed = 0;
600        for n in 0..10 {
601            let ip: IpAddr = format!("10.0.0.{n}").parse().unwrap();
602            allowed += usize::from(instances[n % 2].check(ip, "/sign-in/email", body).await);
603        }
604        assert_eq!(allowed, 5, "the account limit spans clients and instances");
605        assert!(
606            storage
607                .keys()
608                .iter()
609                .all(|key| key.starts_with("fastauth:rate-limit:")
610                    && !key.contains("ada")
611                    && !key.contains("acme")),
612            "{:?}",
613            storage.keys()
614        );
615
616        let other_secret =
617            RateLimiter::new(RateLimit::default(), false, Zeroizing::new([8; 32]), None);
618        assert_eq!(
619            instances[0].account_key("ada@acme.dk"),
620            instances[1].account_key("ada@acme.dk")
621        );
622        assert_ne!(
623            instances[0].account_key("ada@acme.dk"),
624            other_secret.account_key("ada@acme.dk")
625        );
626    }
627
628    #[tokio::test]
629    async fn a_failing_storage_falls_back_to_memory() {
630        let storage = FakeStorage::default();
631        let limiter = shared(sign_in_rule(), &storage);
632        let ip: IpAddr = "203.0.113.7".parse().unwrap();
633        assert!(limiter.check(ip, "/sign-in/email", b"").await);
634        storage.set_down(true);
635        for _ in 0..3 {
636            assert!(limiter.check(ip, "/sign-in/email", b"").await);
637        }
638        assert!(
639            !limiter.check(ip, "/sign-in/email", b"").await,
640            "the in-memory limit still applies"
641        );
642        storage.set_down(false);
643        assert!(
644            limiter.check(ip, "/sign-in/email", b"").await,
645            "the shared counter decides again once the storage answers"
646        );
647    }
648
649    #[tokio::test]
650    async fn a_hanging_storage_costs_a_request_one_timeout() {
651        let storage = FakeStorage::default();
652        let timeout = StdDuration::from_millis(100);
653        let limiter = guarded(
654            sign_in_rule(),
655            GuardedStorage::new(Arc::new(storage.clone()), timeout)
656                .with_breaker(100, StdDuration::ZERO),
657        );
658        storage.set_hanging(true);
659        let ip: IpAddr = "203.0.113.7".parse().unwrap();
660        let body = br#"{"email":"ada@acme.dk"}"#;
661        for n in 1..=3 {
662            let started = Instant::now();
663            assert!(limiter.check(ip, "/sign-in/email", body).await);
664            let took = started.elapsed();
665            assert!(
666                took >= timeout && took < timeout + StdDuration::from_millis(100),
667                "{took:?}"
668            );
669            assert_eq!(
670                storage.increments(),
671                n,
672                "the account bucket stays in memory once the client bucket timed out"
673            );
674        }
675        assert!(
676            !limiter.check(ip, "/sign-in/email", body).await,
677            "the in-memory limit still applies"
678        );
679    }
680
681    #[tokio::test]
682    async fn the_breaker_skips_a_failing_storage_and_probes_it_again() {
683        let storage = FakeStorage::default();
684        let timeout = StdDuration::from_millis(50);
685        let cool_down = StdDuration::from_millis(300);
686        let limiter = guarded(
687            sign_in_rule(),
688            GuardedStorage::new(Arc::new(storage.clone()), timeout).with_breaker(2, cool_down),
689        );
690        let ip: IpAddr = "203.0.113.7".parse().unwrap();
691        storage.set_hanging(true);
692        for _ in 0..2 {
693            assert!(limiter.check(ip, "/sign-in/email", b"").await);
694        }
695        assert_eq!(storage.increments(), 2);
696
697        let started = Instant::now();
698        assert!(limiter.check(ip, "/sign-in/email", b"").await);
699        assert!(
700            !limiter.check(ip, "/sign-in/email", b"").await,
701            "the in-memory limit applies while the breaker is open"
702        );
703        assert!(
704            started.elapsed() < timeout,
705            "skipped calls cost no timeout: {:?}",
706            started.elapsed()
707        );
708        assert_eq!(storage.increments(), 2, "an open breaker skips the storage");
709
710        tokio::time::sleep(cool_down).await;
711        let other: IpAddr = "203.0.113.8".parse().unwrap();
712        let started = Instant::now();
713        assert!(limiter.check(other, "/sign-in/email", b"").await);
714        assert!(
715            started.elapsed() >= timeout,
716            "the probe waits for the storage"
717        );
718        assert!(limiter.check(other, "/sign-in/email", b"").await);
719        assert_eq!(
720            storage.increments(),
721            3,
722            "a failed probe reopens the breaker"
723        );
724
725        storage.set_hanging(false);
726        tokio::time::sleep(cool_down).await;
727        assert!(
728            limiter.check(ip, "/sign-in/email", b"").await,
729            "the probe succeeds and the shared counter decides again"
730        );
731        assert_eq!(storage.increments(), 4);
732        for _ in 0..2 {
733            assert!(limiter.check(ip, "/sign-in/email", b"").await);
734        }
735        assert!(!limiter.check(ip, "/sign-in/email", b"").await);
736        assert_eq!(storage.increments(), 7, "the breaker is closed");
737    }
738
739    #[tokio::test]
740    async fn a_disabled_limiter_never_calls_the_storage() {
741        let storage = FakeStorage::default();
742        let limiter = shared(RateLimit::disabled(), &storage);
743        let ip: IpAddr = "203.0.113.7".parse().unwrap();
744        for _ in 0..200 {
745            assert!(limiter.check(ip, "/sign-in/email", b"").await);
746        }
747        assert!(storage.keys().is_empty());
748    }
749}