ic-bn-lib 0.10.1

Internet Computer Boundary Nodes shared modules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
use std::{
    future::ready,
    hash::Hash,
    net::IpAddr,
    num::NonZeroU32,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

use anyhow::{Error, anyhow};
use arc_swap::ArcSwap;
use axum::{extract::Request, response::IntoResponse, response::Response};
use bytes::Bytes;
use futures::future::BoxFuture;
use governor::{
    Quota,
    clock::{Clock, DefaultClock, Reference},
    middleware::NoOpMiddleware,
    nanos::Nanos,
    state::keyed::DashMapStateStore,
};
use http::{HeaderName, HeaderValue, StatusCode, header::RETRY_AFTER};
use tower::{Layer, Service};

use crate::{constant_time_eq, hname, http::middleware::RemoteAddr};

pub const BYPASS_TOKEN_HEADER: HeaderName = hname!("x-ratelimit-bypass-token");

/// The `governor` rate limiter type that backs this middleware, generic over the clock so
/// that tests can inject `governor::clock::FakeRelativeClock` instead of the real-time
/// default clock.
type GovRateLimiter<K, C> =
    governor::RateLimiter<K, DashMapStateStore<K>, C, NoOpMiddleware<<C as Clock>::Instant>>;

/// Converts a `governor` wait-time into a whole-second `Retry-After` value. Rounds down, but
/// never advertises less than 1 second.
fn retry_after_seconds(wait_time: Duration) -> u32 {
    std::cmp::max(wait_time.as_secs(), 1) as u32
}

/// Extracts a rate-limiting key from the request. Returns `None` if a key cannot be
/// determined, in which case the request is rejected rather than let through unlimited.
pub trait KeyExtractor: Clone + Send + Sync + 'static {
    type Key: Clone + Eq + Hash + Send + Sync + 'static;

    fn extract<B>(&self, req: &Request<B>) -> Option<Self::Key>;
}

/// Decides if the rate-limiting for the given request should be bypassed
pub trait Bypasser: Clone + Send + Sync + 'static {
    fn should_bypass<B>(&self, req: &Request<B>) -> bool;
}

/// Extracts an IP from the request as a rate-limiting key
#[derive(Clone)]
pub struct IpKeyExtractor;

impl KeyExtractor for IpKeyExtractor {
    type Key = IpAddr;

    fn extract<B>(&self, req: &Request<B>) -> Option<Self::Key> {
        req.extensions().get::<RemoteAddr>().map(|x| x.0)
    }
}

/// Extracts a constant key so that all requests share a single rate-limiting bucket
#[derive(Clone)]
pub struct GlobalKeyExtractor;

impl KeyExtractor for GlobalKeyExtractor {
    type Key = ();

    fn extract<B>(&self, _req: &Request<B>) -> Option<Self::Key> {
        Some(())
    }
}

/// Bypasser implementation that checks for a token in the request header `x-ratelimit-bypass-token`
#[derive(Clone)]
pub struct TokenBypasser(Bytes);

impl TokenBypasser {
    pub fn new(token: impl Into<Bytes>) -> Self {
        Self(token.into())
    }
}

impl Bypasser for TokenBypasser {
    fn should_bypass<B>(&self, req: &Request<B>) -> bool {
        req.headers()
            .get(BYPASS_TOKEN_HEADER)
            .map(|x| x.as_bytes())
            .is_some_and(|x| constant_time_eq(x, &self.0))
    }
}

/// Default Bypasser implementation that never bypasses any requests
#[derive(Clone)]
pub struct NeverBypasser;

impl Bypasser for NeverBypasser {
    fn should_bypass<B>(&self, _req: &Request<B>) -> bool {
        false
    }
}

struct RateLimiterState<K: KeyExtractor, R, BP: Bypasser = NeverBypasser, C: Clock = DefaultClock> {
    key_extractor: K,
    limiter: GovRateLimiter<K::Key, C>,
    rate_limited_response: R,
    bypasser: BP,
    last_cleanup: ArcSwap<C::Instant>,
}

/// Ratelimiter that implements Tower Service
#[derive(Clone)]
pub struct RateLimiter<S, K: KeyExtractor, R, BP: Bypasser = NeverBypasser, C: Clock = DefaultClock>
{
    state: Arc<RateLimiterState<K, R, BP, C>>,
    inner: S,
}

/// Implement Tower Service for RateLimiter
impl<S, K, R, BP, C> Service<Request> for RateLimiter<S, K, R, BP, C>
where
    S: Service<Request, Response = Response> + Send + 'static,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
    K: KeyExtractor,
    R: IntoResponse + Clone + Send + Sync + 'static,
    BP: Bypasser,
    C: Clock + Send + Sync + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: Request) -> Self::Future {
        /// Stale entries cleanup interval - 5 minutes
        const CLEANUP_INTERVAL: Nanos = Nanos::new(300_000_000_000);

        // Check that bypasser is configured and tells us to bypass
        let bypass = self.state.bypasser.should_bypass(&request);

        // Clean up stale entries from time to time
        let now = self.state.limiter.clock().now();
        if now.duration_since(*self.state.last_cleanup.load_full()) > CLEANUP_INTERVAL {
            self.state.last_cleanup.store(Arc::new(now));
            self.state.limiter.retain_recent();
        }

        // If bypassing - call the wrapped service directly
        if bypass {
            let fut = self.inner.call(request);
            return Box::pin(fut);
        }

        // Fail if we can't determine a rate-limiting key for the request
        let Some(key) = self.state.key_extractor.extract(&request) else {
            let response = (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Unable to extract rate limiting key",
            )
                .into_response();

            return Box::pin(ready(Ok(response)));
        };

        match self.state.limiter.check_key(&key) {
            Ok(()) => Box::pin(self.inner.call(request)),

            Err(not_until) => {
                let wait_time = not_until.wait_time_from(self.state.limiter.clock().now());
                let retry_secs = retry_after_seconds(wait_time);

                let mut response = self.state.rate_limited_response.clone().into_response();
                let header_value =
                    HeaderValue::from_maybe_shared(Bytes::from(retry_secs.to_string())).unwrap();
                response.headers_mut().insert(RETRY_AFTER, header_value);

                Box::pin(ready(Ok(response)))
            }
        }
    }
}

/// Layer usable as an Axum middleware
#[derive(Clone, derive_new::new)]
pub struct RateLimiterLayer<
    K: KeyExtractor,
    R,
    BP: Bypasser = NeverBypasser,
    C: Clock = DefaultClock,
> {
    state: Arc<RateLimiterState<K, R, BP, C>>,
}

impl<S, K, R, BP, C> Layer<S> for RateLimiterLayer<K, R, BP, C>
where
    S: Clone,
    K: KeyExtractor,
    R: IntoResponse + Clone + Send + Sync + 'static,
    BP: Bypasser,
    C: Clock + Send + Sync + 'static,
{
    type Service = RateLimiter<S, K, R, BP, C>;

    fn layer(&self, inner: S) -> Self::Service {
        RateLimiter {
            inner,
            state: self.state.clone(),
        }
    }
}

/// Create unkeyed rate-limiter
pub fn layer_global<R: IntoResponse + Clone + Send + Sync + 'static, BP: Bypasser>(
    rps: u32,
    burst_size: u32,
    rate_limited_response: R,
    bypasser: BP,
) -> Result<RateLimiterLayer<GlobalKeyExtractor, R, BP>, Error> {
    layer(
        rps,
        burst_size,
        GlobalKeyExtractor,
        rate_limited_response,
        bypasser,
    )
}

/// Create ratelimiter keyed by IP
pub fn layer_by_ip<R: IntoResponse + Clone + Send + Sync + 'static, BP: Bypasser>(
    rps: u32,
    burst_size: u32,
    rate_limited_response: R,
    bypasser: BP,
) -> Result<RateLimiterLayer<IpKeyExtractor, R, BP>, Error> {
    layer(
        rps,
        burst_size,
        IpKeyExtractor,
        rate_limited_response,
        bypasser,
    )
}

/// Create a ratelimiter with a provided key extractor
pub fn layer<K: KeyExtractor, R: IntoResponse + Clone + Send + Sync + 'static, BP: Bypasser>(
    rps: u32,
    burst_size: u32,
    key_extractor: K,
    rate_limited_response: R,
    bypasser: BP,
) -> Result<RateLimiterLayer<K, R, BP>, Error> {
    layer_with_clock(
        rps,
        burst_size,
        key_extractor,
        rate_limited_response,
        bypasser,
        DefaultClock::default(),
    )
}

/// Create a ratelimiter with a provided key extractor and clock. This custom clock is there so
/// that tests can supply a `FakeRelativeClock` and drive the rate limiter's
/// time deterministically, without depending on real wall-clock delays.
fn layer_with_clock<
    K: KeyExtractor,
    R: IntoResponse + Clone + Send + Sync + 'static,
    BP: Bypasser,
    C: Clock,
>(
    rps: u32,
    burst_size: u32,
    key_extractor: K,
    rate_limited_response: R,
    bypasser: BP,
    clock: C,
) -> Result<RateLimiterLayer<K, R, BP, C>, Error> {
    let period = Duration::from_secs(1)
        .checked_div(rps)
        .ok_or_else(|| anyhow!("RPS is zero"))?;

    let burst = NonZeroU32::new(burst_size).ok_or_else(|| anyhow!("burst size is zero"))?;

    let quota = Quota::with_period(period)
        .ok_or_else(|| anyhow!("period is zero"))?
        .allow_burst(burst);

    let limiter = GovRateLimiter::<K::Key, C>::dashmap_with_clock(quota, clock);
    let last_cleanup = ArcSwap::new(limiter.clock().now().into());

    Ok(RateLimiterLayer {
        state: Arc::new(RateLimiterState {
            key_extractor,
            limiter,
            rate_limited_response,
            bypasser,
            last_cleanup,
        }),
    })
}

#[cfg(test)]
mod test {
    use super::*;

    use axum::{
        Router,
        body::{Body, to_bytes},
        extract::Request,
        response::IntoResponse,
        routing::post,
    };
    use governor::clock::FakeRelativeClock;
    use http::{Method, StatusCode};
    use std::str::FromStr;
    use tower::Service;

    async fn handler(_request: Request<Body>) -> impl IntoResponse {
        "test_call"
    }

    async fn send_request(
        router: &mut Router,
        ip: &str,
    ) -> Result<http::Response<Body>, std::convert::Infallible> {
        let mut request = Request::post("/").body(Body::from("".to_string())).unwrap();
        request
            .extensions_mut()
            .insert(RemoteAddr(IpAddr::from_str(ip).unwrap()));
        router.call(request).await
    }

    fn retry_after_header(response: &http::Response<Body>) -> u32 {
        response
            .headers()
            .get(http::header::RETRY_AFTER)
            .expect("Retry-After header missing on 429 response")
            .to_str()
            .unwrap()
            .parse()
            .unwrap()
    }

    #[test]
    fn test_retry_after_seconds() {
        // Rounds down, but never below 1 second
        assert_eq!(retry_after_seconds(Duration::from_millis(0)), 1);
        assert_eq!(retry_after_seconds(Duration::from_millis(500)), 1);
        assert_eq!(retry_after_seconds(Duration::from_millis(999)), 1);
        assert_eq!(retry_after_seconds(Duration::from_millis(1000)), 1);
        assert_eq!(retry_after_seconds(Duration::from_millis(1999)), 1);
        assert_eq!(retry_after_seconds(Duration::from_millis(2000)), 2);
        assert_eq!(retry_after_seconds(Duration::from_millis(2999)), 2);
        assert_eq!(retry_after_seconds(Duration::from_secs(10)), 10);
    }

    #[test]
    fn test_layer_rejects_zero_rps() {
        assert!(
            layer(
                0,
                5,
                IpKeyExtractor,
                (StatusCode::TOO_MANY_REQUESTS, "foo"),
                NeverBypasser,
            )
            .is_err()
        );
    }

    #[test]
    fn test_layer_rejects_zero_burst_size() {
        assert!(
            layer(
                5,
                0,
                IpKeyExtractor,
                (StatusCode::TOO_MANY_REQUESTS, "foo"),
                NeverBypasser,
            )
            .is_err()
        );
    }

    // Uses a `FakeRelativeClock` so token refills are driven by explicit
    // advances rather than sleeps
    #[tokio::test(start_paused = true)]
    async fn test_rate_limiter_rps_limit() {
        let rps = 5;
        let burst_size = 5; // how many requests can go through at once (without delay)
        let period = Duration::from_secs(1) / rps; // time for one token to refill

        let clock = FakeRelativeClock::default();
        let rate_limiter_mw = layer_with_clock(
            rps,
            burst_size,
            IpKeyExtractor,
            (StatusCode::TOO_MANY_REQUESTS, "foo"),
            NeverBypasser,
            clock.clone(),
        )
        .expect("failed to build middleware");

        let mut app = Router::new()
            .route("/", post(handler))
            .layer(rate_limiter_mw);

        // Initial burst of 5 requests should succeed and fills full burst capacity
        for _ in 0..5 {
            let result = send_request(&mut app, "1.1.1.1").await.unwrap();
            assert_eq!(result.status(), StatusCode::OK);
        }

        // For 6th request no tokens left => 429
        let result = send_request(&mut app, "1.1.1.1").await.unwrap();
        assert_eq!(result.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(retry_after_header(&result), 1);

        // Advance the fake clock by exactly one token's worth of time (no real waiting)
        clock.advance(period);
        let result = send_request(&mut app, "1.1.1.1").await.unwrap();
        assert_eq!(result.status(), StatusCode::OK);

        // Bucket is empty again, request should fail
        let result = send_request(&mut app, "1.1.1.1").await.unwrap();
        assert_eq!(result.status(), StatusCode::TOO_MANY_REQUESTS);

        // Advance for 2 tokens to be available, next 2 requests succeed
        clock.advance(2 * period);
        for _ in 0..2 {
            let result = send_request(&mut app, "1.1.1.1").await.unwrap();
            assert_eq!(result.status(), StatusCode::OK);
        }

        // Bucket is empty again, request should fail
        let result = send_request(&mut app, "1.1.1.1").await.unwrap();
        assert_eq!(result.status(), StatusCode::TOO_MANY_REQUESTS);

        // Advance for 5 tokens (full burst), next 5 requests succeed
        clock.advance(5 * period);
        for _ in 0..5 {
            let result = send_request(&mut app, "1.1.1.1").await.unwrap();
            assert_eq!(result.status(), StatusCode::OK);
        }

        // Bucket is empty again, requests should fail
        for _ in 0..2 {
            let result = send_request(&mut app, "1.1.1.1").await.unwrap();
            assert_eq!(result.status(), StatusCode::TOO_MANY_REQUESTS);
        }
    }

    #[tokio::test(start_paused = true)]
    async fn test_rate_limiter_retry_after_decreases_as_clock_advances() {
        let clock = FakeRelativeClock::default();
        let rate_limiter_mw = layer_with_clock(
            1,
            1,
            IpKeyExtractor,
            (StatusCode::TOO_MANY_REQUESTS, "foo"),
            NeverBypasser,
            clock.clone(),
        )
        .expect("failed to build middleware");

        let mut app = Router::new()
            .route("/", post(handler))
            .layer(rate_limiter_mw);

        // Consume the only token
        let result = send_request(&mut app, "1.1.1.1").await.unwrap();
        assert_eq!(result.status(), StatusCode::OK);

        // Full period (1s) remaining
        let result = send_request(&mut app, "1.1.1.1").await.unwrap();
        assert_eq!(result.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(retry_after_header(&result), 1);

        // Once the period has fully elapsed the token is available again
        clock.advance(Duration::from_secs(1));
        let result = send_request(&mut app, "1.1.1.1").await.unwrap();
        assert_eq!(result.status(), StatusCode::OK);
    }

    #[tokio::test(start_paused = true)]
    async fn test_rate_limiter_per_key_independence() {
        let clock = FakeRelativeClock::default();
        let rate_limiter_mw = layer_with_clock(
            1,
            1,
            IpKeyExtractor,
            (StatusCode::TOO_MANY_REQUESTS, "foo"),
            NeverBypasser,
            clock.clone(),
        )
        .expect("failed to build middleware");

        let mut app = Router::new()
            .route("/", post(handler))
            .layer(rate_limiter_mw);

        // IP A consumes its only token and gets rate-limited
        assert_eq!(
            send_request(&mut app, "1.1.1.1").await.unwrap().status(),
            StatusCode::OK
        );
        assert_eq!(
            send_request(&mut app, "1.1.1.1").await.unwrap().status(),
            StatusCode::TOO_MANY_REQUESTS
        );

        // IP B has its own independent bucket and is unaffected
        assert_eq!(
            send_request(&mut app, "2.2.2.2").await.unwrap().status(),
            StatusCode::OK
        );
        assert_eq!(
            send_request(&mut app, "2.2.2.2").await.unwrap().status(),
            StatusCode::TOO_MANY_REQUESTS
        );
    }

    #[tokio::test(start_paused = true)]
    async fn test_rate_limiter_returns_server_error() {
        let rps = 1;
        let burst_size = 1;

        let rate_limiter_mw = layer(
            rps,
            burst_size,
            IpKeyExtractor,
            (StatusCode::TOO_MANY_REQUESTS, "foo"),
            NeverBypasser,
        )
        .expect("failed to build middleware");

        let mut app = Router::new()
            .route("/", post(handler))
            .layer(rate_limiter_mw);

        // Send request without connection info, i.e. without ip address.
        let request = Request::post("/").body(Body::from("".to_string())).unwrap();
        let result = app.call(request).await.unwrap();

        assert_eq!(result.status(), StatusCode::INTERNAL_SERVER_ERROR);
        let body = to_bytes(result.into_body(), 1024).await.unwrap().to_vec();
        assert_eq!(body, b"Unable to extract rate limiting key");
    }

    #[tokio::test(start_paused = true)]
    async fn test_rate_limiter_bypass_token() {
        let rate_limiter_mw = layer(
            1,
            10,
            GlobalKeyExtractor,
            (StatusCode::TOO_MANY_REQUESTS, "foo"),
            TokenBypasser::new("top_secret_token"),
        )
        .expect("failed to build middleware");

        let mut app = Router::new()
            .route("/", post(handler))
            .layer(rate_limiter_mw);

        // First 10 pass
        for _ in 0..10 {
            let req = Request::builder()
                .method(Method::POST)
                .body(Body::empty())
                .unwrap();
            let res = app.call(req).await.unwrap();
            assert_eq!(res.status(), StatusCode::OK);
        }

        // Then all blocked
        for _ in 0..100 {
            let req = Request::builder()
                .method(Method::POST)
                .body(Body::empty())
                .unwrap();
            let res = app.call(req).await.unwrap();
            assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
        }

        // But pass with a token
        for _ in 0..100 {
            let req = Request::builder()
                .method(Method::POST)
                .header(BYPASS_TOKEN_HEADER, "top_secret_token")
                .body(Body::empty())
                .unwrap();
            let res = app.call(req).await.unwrap();
            assert_eq!(res.status(), StatusCode::OK);
        }

        // And doesn't work with a bad token
        for _ in 0..100 {
            let req = Request::builder()
                .method(Method::POST)
                .header(BYPASS_TOKEN_HEADER, "not_very_secret")
                .body(Body::empty())
                .unwrap();
            let res = app.call(req).await.unwrap();
            assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
        }
    }

    #[tokio::test(start_paused = true)]
    async fn test_rate_limiter_cleans_up_stale_entries() {
        let clock = FakeRelativeClock::default();
        let rate_limiter_mw = layer_with_clock(
            1,
            1,
            IpKeyExtractor,
            (StatusCode::TOO_MANY_REQUESTS, "foo"),
            NeverBypasser,
            clock.clone(),
        )
        .expect("failed to build middleware");

        // Keep a handle to the underlying governor limiter so we can observe how many
        // keys it's tracking, independently of the middleware wrapping it.
        let state = rate_limiter_mw.state.clone();
        let limiter = &state.limiter;

        let mut app = Router::new()
            .route("/", post(handler))
            .layer(rate_limiter_mw);

        // Two distinct keys get tracked in the limiter's state
        send_request(&mut app, "1.1.1.1").await.unwrap();
        send_request(&mut app, "2.2.2.2").await.unwrap();
        assert_eq!(limiter.len(), 2);

        // Advancing by less than the cleanup interval (10 minutes) leaves stale
        // entries in place, even though their buckets have long since refilled.
        clock.advance(Duration::from_secs(60));
        send_request(&mut app, "3.3.3.3").await.unwrap();
        assert_eq!(limiter.len(), 3);

        // Once the cleanup interval has elapsed, the next request triggers a sweep
        // that drops entries indistinguishable from a fresh bucket -- i.e. all three
        // previously-seen keys -- before the new key is inserted.
        clock.advance(Duration::from_secs(600));
        send_request(&mut app, "4.4.4.4").await.unwrap();
        assert_eq!(limiter.len(), 1);
    }

    #[tokio::test(start_paused = true)]
    async fn test_layer_global_wrapper() {
        let rate_limiter_mw =
            layer_global(2, 2, (StatusCode::TOO_MANY_REQUESTS, "foo"), NeverBypasser).unwrap();

        let mut app = Router::new()
            .route("/", post(handler))
            .layer(rate_limiter_mw);

        for _ in 0..2 {
            let req = Request::builder()
                .method(Method::POST)
                .body(Body::empty())
                .unwrap();
            let res = app.call(req).await.unwrap();
            assert_eq!(res.status(), StatusCode::OK);
        }

        let req = Request::builder()
            .method(Method::POST)
            .body(Body::empty())
            .unwrap();
        let res = app.call(req).await.unwrap();
        assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
    }

    #[tokio::test(start_paused = true)]
    async fn test_layer_by_ip_wrapper() {
        let rate_limiter_mw =
            layer_by_ip(2, 2, (StatusCode::TOO_MANY_REQUESTS, "foo"), NeverBypasser).unwrap();

        let mut app = Router::new()
            .route("/", post(handler))
            .layer(rate_limiter_mw);

        for _ in 0..2 {
            let result = send_request(&mut app, "1.1.1.1").await.unwrap();
            assert_eq!(result.status(), StatusCode::OK);
        }

        let result = send_request(&mut app, "1.1.1.1").await.unwrap();
        assert_eq!(result.status(), StatusCode::TOO_MANY_REQUESTS);
    }
}