footing 0.6.1

Feature-gated foundations for Rust backend services
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
use std::time::{Duration, Instant};

use axum::http::{HeaderName, Request};

use super::*;
use crate::result::{ClassifyError, ErrorKind};

#[test]
fn idle_cleanup_does_not_reset_unreplenished_allowances() {
    let now = Instant::now();
    let last_request = now - Duration::from_secs(10);
    let limiter =
        TokenBucketRateLimiter::new(RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap());
    assert!(limiter.check_at("key", last_request).unwrap().is_allowed());
    assert_eq!(
        limiter.prune_idle_at(Duration::from_secs(5), now).unwrap(),
        0
    );
    assert!(!limiter.check_at("key", now).unwrap().is_allowed());
}

#[test]
fn freeing_tracked_slots_does_not_reset_an_exhausted_overflow_bucket() {
    for explicit_cleanup in [false, true] {
        let now = Instant::now();
        let limiter = TokenBucketRateLimiter::with_max_buckets(
            RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap(),
            1,
        )
        .unwrap();
        assert!(limiter.check_at("tracked", now).unwrap().is_allowed());
        assert!(limiter.check_at("overflow", now).unwrap().is_allowed());
        assert!(limiter.check_at("overflow", now).unwrap().is_allowed());
        let cleanup_at = now + Duration::from_secs(10);
        if explicit_cleanup {
            assert_eq!(
                limiter
                    .prune_idle_at(Duration::from_secs(1), cleanup_at)
                    .unwrap(),
                1
            );
        }
        // The tracked bucket is full; overflow has earned only one token.
        assert_eq!(
            limiter.check_at("overflow", cleanup_at).unwrap(),
            RateLimitDecision::allowed(0)
        );
        for key in ["overflow", "new", "tracked"] {
            assert!(!limiter.check_at(key, cleanup_at).unwrap().is_allowed());
        }
        assert_eq!(limiter.bucket_count().unwrap(), 0);
        for _ in 0..2 {
            assert!(
                limiter
                    .check_at("new", now + Duration::from_secs(30))
                    .unwrap()
                    .is_allowed()
            );
        }
        assert!(
            !limiter
                .check_at("new", now + Duration::from_secs(30))
                .unwrap()
                .is_allowed()
        );
    }
}

#[test]
fn full_overflow_bucket_preserves_its_refill_remainder_while_storage_is_full() {
    let start = Instant::now();
    let limiter = TokenBucketRateLimiter::with_max_buckets(
        RateLimitConfig::new(1, 1, Duration::from_secs(10)).unwrap(),
        1,
    )
    .unwrap();
    for (key, seconds) in [
        ("tracked", 0),
        ("overflow", 5),
        ("tracked", 10),
        ("overflow", 16),
        ("tracked", 20),
    ] {
        assert!(
            limiter
                .check_at(key, start + Duration::from_secs(seconds))
                .unwrap()
                .is_allowed()
        );
    }
    // Overflow refilled at t=15; consuming it at t=16 must preserve the next
    // refill at t=25, even though the tracked bucket is still occupied.
    assert_eq!(
        limiter
            .check_at("overflow", start + Duration::from_secs(24))
            .unwrap(),
        RateLimitDecision::denied(Duration::from_secs(1))
    );
    assert!(
        limiter
            .check_at("overflow", start + Duration::from_secs(25))
            .unwrap()
            .is_allowed()
    );
    assert_eq!(limiter.bucket_count().unwrap(), 1);
}

#[tokio::test]
async fn store_owned_clock_keeps_denials_idle_time_and_full_refill_consistent() {
    use std::sync::Arc;

    let clock = crate::clock::ManualClock::new();
    let config = RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap();
    let store: Arc<dyn RateLimitStore> =
        Arc::new(TokenBucketRateLimiter::new(config).with_clock(clock.shared()));
    for _ in 0..2 {
        assert!(
            store
                .check("key".into(), config)
                .await
                .unwrap()
                .is_allowed()
        );
    }
    clock.advance(Duration::from_secs(5)).unwrap();
    assert!(
        !store
            .check("key".into(), config)
            .await
            .unwrap()
            .is_allowed()
    );
    // Old enough to prune, but only half the capacity has replenished.
    clock.advance(Duration::from_secs(5)).unwrap();
    assert_eq!(store.prune_idle(Duration::from_secs(1)).await.unwrap(), 0);
    // Full, but the denied check counts as recent activity.
    clock.advance(Duration::from_secs(10)).unwrap();
    assert_eq!(store.prune_idle(Duration::from_secs(16)).await.unwrap(), 0);
    assert_eq!(store.prune_idle(Duration::MAX).await.unwrap(), 0);
    assert_eq!(store.prune_idle(Duration::from_secs(15)).await.unwrap(), 1);
    assert!(
        store
            .check("key".into(), config)
            .await
            .unwrap()
            .is_allowed()
    );
    assert!(
        store
            .check("key".into(), config)
            .await
            .unwrap()
            .is_allowed()
    );
    assert!(
        !store
            .check("key".into(), config)
            .await
            .unwrap()
            .is_allowed()
    );
}

#[test]
fn limiter_accepts_non_clone_keys_and_preserves_overflow_limits() {
    #[derive(PartialEq, Eq, Hash)]
    struct Key(u32);

    let config = RateLimitConfig::new(1, 1, Duration::from_secs(10)).unwrap();
    let limiter = TokenBucketRateLimiter::with_max_buckets(config, 1).unwrap();
    let now = Instant::now();
    assert!(limiter.check_at(Key(1), now).unwrap().is_allowed());
    assert!(!limiter.check_at(Key(1), now).unwrap().is_allowed());
    assert!(limiter.check_at(Key(2), now).unwrap().is_allowed());
    assert!(!limiter.check_at(Key(3), now).unwrap().is_allowed());
    assert_eq!(limiter.bucket_count().unwrap(), 1);
    assert!(
        limiter
            .check_at(Key(3), now + Duration::from_secs(10))
            .unwrap()
            .is_allowed()
    );
    assert!(
        !limiter
            .check_at(Key(3), now + Duration::from_secs(10))
            .unwrap()
            .is_allowed()
    );
}

#[tokio::test]
async fn metric_capacity_failures_are_shared_without_changing_rate_limit_decisions() {
    use crate::observability::{MetricLabels, MetricRegistry, MetricRegistryLimits};
    use std::sync::Arc;

    let metrics = Arc::new(MetricRegistry::with_limits(
        MetricRegistryLimits::new(1, 1).unwrap(),
    ));
    metrics
        .increment_counter("occupied", 1, MetricLabels::default())
        .unwrap();
    let runtime = RateLimitRuntime::in_memory(
        RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap(),
        RateLimitKeySource::Fixed("bucket".into()),
    )
    .with_metrics(Some(metrics));
    let clone = runtime.clone();
    assert!(enforce_rate_limit(&clone, &Request::new(())).await.is_ok());
    assert!(matches!(
        enforce_rate_limit(&clone, &Request::new(())).await,
        Err(RateLimitRejection::Limited { .. })
    ));
    assert_eq!(runtime.failed_recordings(), 2);
}

#[tokio::test]
async fn store_errors_are_counted_without_decisions_or_private_backend_details() {
    use crate::observability::{MetricLabels, MetricRegistry, MetricRegistryLimits, metric_names};
    use std::sync::Arc;

    struct FailingStore;
    #[async_trait::async_trait]
    impl RateLimitStore for FailingStore {
        async fn check(
            &self,
            _: String,
            _: RateLimitConfig,
        ) -> Result<RateLimitDecision, RateLimitError> {
            Err(RateLimitError::Store(
                std::io::Error::other("private backend address").into(),
            ))
        }

        async fn prune_idle(&self, _: Duration) -> Result<usize, RateLimitError> {
            Ok(0)
        }
    }

    for full_metrics in [false, true] {
        let metrics = Arc::new(MetricRegistry::with_limits(
            MetricRegistryLimits::new(1, 1).unwrap(),
        ));
        if full_metrics {
            metrics
                .increment_counter("occupied", 1, MetricLabels::default())
                .unwrap();
        }
        let config = RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap();
        let runtime = RateLimitRuntime::new(
            config,
            RateLimitKeySource::Fixed("private bucket".into()),
            Arc::new(FailingStore),
        )
        .with_metrics(Some(metrics.clone()));
        for _ in 0..2 {
            assert_eq!(
                enforce_rate_limit(&runtime.clone(), &Request::new(())).await,
                Err(RateLimitRejection::Unavailable),
            );
        }
        // Missing identity is not a store operation and must not increment this counter.
        let missing_key = RateLimitRuntime::new(
            config,
            RateLimitKeySource::Principal,
            Arc::new(FailingStore),
        )
        .with_metrics(Some(metrics.clone()));
        assert_eq!(
            enforce_rate_limit(&missing_key, &Request::new(())).await,
            Err(RateLimitRejection::MissingKey)
        );
        assert_eq!(
            runtime.failed_recordings(),
            if full_metrics { 2 } else { 0 }
        );
        assert_eq!(missing_key.failed_recordings(), 0);
        let snapshot = metrics.snapshot().unwrap();
        assert_eq!(snapshot.samples().len(), 1);
        if !full_metrics {
            let sample = &snapshot.samples()[0];
            assert_eq!(sample.name(), metric_names::RATE_LIMIT_STORE_ERRORS_TOTAL);
            assert_eq!(sample.value(), 2.0);
            assert_eq!(
                sample.labels(),
                MetricLabels::new([
                    ("stage", "check"),
                    ("error_code", "rate_limit_store_unavailable"),
                ])
                .unwrap()
                .as_slice()
            );
        }
    }
}

#[tokio::test]
async fn runtime_uses_the_existing_limiter_state_and_store_contract() {
    let config = RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap();
    let now = Instant::now();
    let clock = crate::clock::ManualClock::at(now);
    let limiter =
        std::sync::Arc::new(TokenBucketRateLimiter::new(config).with_clock(clock.shared()));
    let runtime =
        RateLimitRuntime::from_limiter(limiter.clone(), RateLimitKeySource::Fixed("test".into()));
    assert!(
        limiter
            .check_at("key".to_owned(), now)
            .unwrap()
            .is_allowed()
    );
    assert!(
        !runtime
            .store()
            .check("key".to_owned(), config)
            .await
            .unwrap()
            .is_allowed()
    );
    assert_eq!(runtime.store().prune_idle(Duration::ZERO).await.unwrap(), 0);
    clock.advance(Duration::from_secs(60)).unwrap();
    assert_eq!(runtime.store().prune_idle(Duration::ZERO).await.unwrap(), 1);
    assert!(limiter.check("key".to_owned()).unwrap().is_allowed());
}

#[test]
fn mismatched_policy_cannot_reset_regular_or_overflow_allowances() {
    let slow = RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap();
    let limiter = TokenBucketRateLimiter::with_max_buckets(slow, 1).unwrap();
    let now = Instant::now();
    assert!(limiter.check_at("regular", now).unwrap().is_allowed());
    assert!(limiter.check_at("overflow", now).unwrap().is_allowed());

    let later = now + Duration::from_secs(2);
    for other in [
        RateLimitConfig::new(1, 1, Duration::from_secs(1)).unwrap(),
        RateLimitConfig::new(2, 1, Duration::from_secs(3600)).unwrap(),
        RateLimitConfig::new(1, 2, Duration::from_secs(3600)).unwrap(),
    ] {
        for key in ["regular", "overflow", "new"] {
            let error = limiter.check_at_with_config(key, other, later).unwrap_err();
            assert!(matches!(error, RateLimitError::ConfigMismatch));
            assert_eq!(error.error_kind(), ErrorKind::Validation);
            assert_eq!(error.error_code(), "rate_limit_config_mismatch");
        }
    }
    assert_eq!(limiter.bucket_count().unwrap(), 1);
    assert!(!limiter.check_at("regular", later).unwrap().is_allowed());
    assert!(!limiter.check_at("overflow", later).unwrap().is_allowed());
    assert!(!limiter.check_at("new", later).unwrap().is_allowed());
    assert!(
        limiter
            .check_at("regular", now + Duration::from_secs(3600))
            .unwrap()
            .is_allowed()
    );
}

#[tokio::test]
async fn runtime_rejects_a_policy_incompatible_with_its_memory_store() {
    let slow = RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap();
    let fast = RateLimitConfig::new(1, 1, Duration::from_secs(1)).unwrap();
    let runtime = RateLimitRuntime::new(
        fast,
        RateLimitKeySource::Fixed("account".into()),
        std::sync::Arc::new(TokenBucketRateLimiter::new(slow)),
    );
    assert_eq!(
        enforce_rate_limit(&runtime, &Request::new(())).await,
        Err(RateLimitRejection::Unavailable)
    );
}

#[test]
fn token_bucket_denies_after_capacity_and_refills() {
    let config = RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap();
    let limiter = TokenBucketRateLimiter::new(config);
    let now = Instant::now();

    assert!(limiter.check_at("user", now).unwrap().is_allowed());
    assert!(limiter.check_at("user", now).unwrap().is_allowed());
    assert!(!limiter.check_at("user", now).unwrap().is_allowed());
    assert!(
        limiter
            .check_at("user", now + Duration::from_secs(10))
            .unwrap()
            .is_allowed()
    );
}

#[test]
fn token_bucket_preserves_latest_activity_when_checks_arrive_out_of_order() {
    let refill_period = Duration::from_secs(10);
    let limiter = TokenBucketRateLimiter::new(RateLimitConfig::new(1, 1, refill_period).unwrap());
    let earlier = Instant::now();
    let later = earlier + Duration::from_millis(2);

    // Concurrent callers can sample time in one order and acquire the lock in another.
    assert!(limiter.check_at("user", later).unwrap().is_allowed());
    assert!(!limiter.check_at("user", earlier).unwrap().is_allowed());

    // Even a full-refill idle threshold must preserve this recently used bucket.
    let cleanup_at = earlier + refill_period + Duration::from_millis(1);
    let removed = limiter.prune_idle_at(refill_period, cleanup_at).unwrap();
    assert!(
        !limiter.check_at("user", cleanup_at).unwrap().is_allowed(),
        "idle cleanup must not reset an allowance before its refill is due"
    );
    assert_eq!(removed, 0);
    assert!(
        limiter
            .check_at("user", later + refill_period)
            .unwrap()
            .is_allowed()
    );
}

#[test]
fn token_bucket_preserves_the_refill_remainder_across_the_duration_range() {
    let start = Instant::now();
    for (interval, elapsed, retry_after) in [
        (
            Duration::from_millis(10),
            Duration::from_millis(15),
            Duration::from_millis(5),
        ),
        (
            Duration::from_secs(40_000_000_000),
            Duration::from_secs(70_000_000_000),
            Duration::from_secs(10_000_000_000),
        ),
    ] {
        // Some platforms cannot represent instants beyond u64 nanoseconds.
        let Some(later) = start.checked_add(elapsed) else {
            continue;
        };
        let limiter = TokenBucketRateLimiter::new(RateLimitConfig::new(1, 1, interval).unwrap());
        assert!(limiter.check_at("key", start).unwrap().is_allowed());
        assert!(limiter.check_at("key", later).unwrap().is_allowed());
        assert_eq!(
            limiter.check_at("key", later).unwrap().retry_after(),
            Some(retry_after),
        );
    }
}

#[test]
fn rate_limit_debug_does_not_expose_bucket_or_fixed_keys() {
    let config = RateLimitConfig::new(2, 1, Duration::from_secs(10)).unwrap();
    let limiter = TokenBucketRateLimiter::new(config);
    let private_key = "private-account-rate-limit-key";
    limiter
        .check(private_key.to_owned())
        .expect("rate limit check should succeed");

    let output = format!(
        "{limiter:?} {:?}",
        RateLimitKeySource::Fixed(private_key.to_owned())
    );
    assert!(output.contains("bucket_count"));
    assert!(output.contains("[REDACTED]"));
    assert!(!output.contains(private_key));
}

#[test]
fn rate_limit_config_rejects_zero_refill_interval() {
    let error = RateLimitConfig::new(2, 1, Duration::ZERO)
        .expect_err("zero refill interval must be rejected at construction");
    assert!(matches!(error, RateLimitError::InvalidRefillInterval));
}

#[test]
fn token_bucket_uses_bounded_overflow_bucket_for_excess_keys() {
    let limiter = TokenBucketRateLimiter::with_max_buckets(
        RateLimitConfig::new(1, 1, Duration::from_secs(10)).unwrap(),
        2,
    )
    .unwrap();
    let now = Instant::now();

    assert!(limiter.check_at("first", now).unwrap().is_allowed());
    assert!(limiter.check_at("second", now).unwrap().is_allowed());
    assert!(limiter.check_at("third", now).unwrap().is_allowed());
    assert!(
        !limiter.check_at("fourth", now).unwrap().is_allowed(),
        "all excess keys should share one bounded overflow bucket"
    );
    assert_eq!(limiter.bucket_count().unwrap(), 2);
    assert!(!limiter.check_at("first", now).unwrap().is_allowed());
    assert_eq!(limiter.bucket_count().unwrap(), 2);

    assert!(
        limiter
            .check_at("third", now + Duration::from_secs(10))
            .unwrap()
            .is_allowed()
    );
    assert_eq!(limiter.bucket_count().unwrap(), 1);
}

#[test]
fn header_key_source_hashes_and_bounds_untrusted_values() {
    let source =
        RateLimitKeySource::trusted_header_from_upstream(HeaderName::from_static("x-account-id"));
    let private_value = "private-account-identifier";
    let request = Request::builder()
        .header("x-account-id", private_value)
        .body(())
        .expect("request should build");

    let key = source.key_for(&request).expect("header key should exist");
    assert!(key.starts_with("header:"));
    assert!(!key.contains(private_value));
    assert_eq!(source.key_for(&request).as_deref(), Some(key.as_str()));

    let oversized = Request::builder()
        .header(
            "x-account-id",
            "x".repeat(MAX_RATE_LIMIT_HEADER_VALUE_BYTES + 1),
        )
        .body(())
        .expect("request should build");
    assert!(source.key_for(&oversized).is_none());
}

#[tokio::test]
async fn rate_limit_layer_accepts_wrapped_request_bodies() {
    use axum::{body::Body, http::StatusCode, response::Response};
    use http_body_util::BodyExt as _;
    use tower::{Layer as _, ServiceExt as _};
    use tower_http::timeout::{RequestBodyTimeoutLayer, TimeoutBody};

    let runtime = RateLimitRuntime::in_memory(
        RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap(),
        RateLimitKeySource::Fixed("account".into()),
    );
    let inner = tower::service_fn(|request: Request<TimeoutBody<Body>>| async move {
        let body = request.into_body().collect().await.unwrap().to_bytes();
        Ok::<_, std::convert::Infallible>(Response::new(Body::from(body)))
    });
    let service = RequestBodyTimeoutLayer::new(Duration::from_secs(1))
        .layer(RateLimitLayer::new(runtime).layer(inner));
    let response = service
        .clone()
        .oneshot(Request::new(Body::from("request body")))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        response.into_body().collect().await.unwrap().to_bytes(),
        "request body"
    );
    let response = service.oneshot(Request::new(Body::empty())).await.unwrap();
    assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
}

#[tokio::test]
async fn middleware_rejections_preserve_context_and_retry_after() {
    use std::sync::Arc;

    use axum::{
        body::{Body, to_bytes},
        http::{StatusCode, header},
        response::Response,
    };
    use tower::{Layer as _, ServiceExt as _};

    use crate::http::{RequestContext, RequestId, TraceParent};

    let config = RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap();
    let clock = crate::clock::ManualClock::new();
    let limited = RateLimitRuntime::from_limiter(
        Arc::new(TokenBucketRateLimiter::new(config).with_clock(clock.shared())),
        RateLimitKeySource::Fixed("account".into()),
    );
    enforce_rate_limit(&limited, &Request::new(()))
        .await
        .unwrap();
    let missing = RateLimitRuntime::in_memory(config, RateLimitKeySource::Principal);
    let unavailable = RateLimitRuntime::new(
        config,
        RateLimitKeySource::Fixed("account".into()),
        Arc::new(TokenBucketRateLimiter::new(
            RateLimitConfig::new(2, 1, Duration::from_secs(60)).unwrap(),
        )),
    );

    for (runtime, status, code) in [
        (limited, StatusCode::TOO_MANY_REQUESTS, "rate_limited"),
        (
            missing,
            StatusCode::SERVICE_UNAVAILABLE,
            "rate_limit_key_unavailable",
        ),
        (
            unavailable,
            StatusCode::SERVICE_UNAVAILABLE,
            "rate_limit_unavailable",
        ),
    ] {
        for with_context in [false, true] {
            let service = RateLimitLayer::new(runtime.clone()).layer(tower::service_fn(
                |_: Request<()>| async {
                    Ok::<_, std::convert::Infallible>(Response::new(Body::empty()))
                },
            ));
            let mut request = Request::builder()
                .header("x-request-id", "untrusted-request")
                .body(())
                .unwrap();
            if with_context {
                request.extensions_mut().insert(
                    RequestContext::new(RequestId::new("verified-request").unwrap())
                        .with_traceparent(
                            TraceParent::new(
                                "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
                            )
                            .unwrap(),
                        )
                        .with_session_id("private-session"),
                );
            }
            let response = service.oneshot(request).await.unwrap();
            assert_eq!(response.status(), status);
            assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
            let retry_after = response.headers().get(header::RETRY_AFTER);
            if status == StatusCode::TOO_MANY_REQUESTS {
                assert_eq!(retry_after.unwrap(), "60");
            } else {
                assert!(retry_after.is_none());
            }
            let bytes = to_bytes(response.into_body(), 4096).await.unwrap();
            let problem: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
            assert_eq!(problem["code"], code);
            if with_context {
                assert_eq!(problem["request_id"], "verified-request");
                assert_eq!(problem["trace_id"], "4bf92f3577b34da6a3ce929d0e0e4736");
            } else {
                assert!(problem.get("request_id").is_none());
                assert!(problem.get("trace_id").is_none());
            }
            assert!(!String::from_utf8_lossy(&bytes).contains("private-session"));
        }
    }
}

#[tokio::test]
async fn rate_limit_layer_preserves_non_send_errors_and_consumes_allowance() {
    use axum::{http::StatusCode, response::Response};
    use tower::{Layer as _, ServiceExt as _};

    let clock = crate::clock::ManualClock::new();
    let runtime = RateLimitRuntime::from_limiter(
        std::sync::Arc::new(
            TokenBucketRateLimiter::new(
                RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap(),
            )
            .with_clock(clock.shared()),
        ),
        RateLimitKeySource::Fixed("account".into()),
    );
    let inner = tower::service_fn(|_: Request<()>| async {
        tokio::task::yield_now().await;
        Err::<Response, _>(std::rc::Rc::new(String::from("local service failure")))
    });
    let service = RateLimitLayer::new(runtime).layer(inner);

    let error = service.clone().oneshot(Request::new(())).await.unwrap_err();
    assert_eq!(error.as_str(), "local service failure");

    let response = service.oneshot(Request::new(())).await.unwrap();
    assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
    assert_eq!(response.headers()[axum::http::header::RETRY_AFTER], "60");
}

#[tokio::test]
async fn missing_stable_key_fails_closed_instead_of_sharing_anonymous_bucket() {
    let runtime = RateLimitRuntime::in_memory(
        RateLimitConfig::new(1, 1, Duration::from_secs(60)).unwrap(),
        RateLimitKeySource::Principal,
    );
    let request = Request::new(());

    assert_eq!(
        enforce_rate_limit(&runtime, &request).await,
        Err(RateLimitRejection::MissingKey)
    );
}

#[tokio::test]
async fn repeated_trusted_headers_fail_closed_without_consuming_tokens() {
    use axum::{body::to_bytes, http::StatusCode, response::IntoResponse as _};

    let runtime = RateLimitRuntime::in_memory(
        RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap(),
        RateLimitKeySource::trusted_header_from_upstream(HeaderName::from_static("x-account-id")),
    );
    for second in ["account", "other"] {
        let request = Request::builder()
            .header("x-account-id", "account")
            .header("x-account-id", second)
            .body(())
            .unwrap();
        let rejection = enforce_rate_limit(&runtime, &request).await.unwrap_err();
        assert_eq!(rejection, RateLimitRejection::MissingKey);
        let response = rejection.into_response();
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = to_bytes(response.into_body(), 4096).await.unwrap();
        let problem: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(problem["code"], "rate_limit_key_unavailable");
    }
    let request = Request::builder()
        .header("x-account-id", "account")
        .body(())
        .unwrap();
    assert!(enforce_rate_limit(&runtime, &request).await.is_ok());
}

#[test]
fn retry_after_header_seconds_rounds_subsecond_delays_up() {
    assert_eq!(retry_after_header_seconds(Duration::ZERO), 0);
    assert_eq!(retry_after_header_seconds(Duration::from_millis(1)), 1);
    assert_eq!(retry_after_header_seconds(Duration::from_millis(1500)), 2);
    assert_eq!(retry_after_header_seconds(Duration::from_secs(3)), 3);
}

#[test]
fn rate_limit_decision_encodes_allowed_and_denied_invariants() {
    let allowed = RateLimitDecision::allowed(7);
    assert!(allowed.is_allowed());
    assert_eq!(allowed.remaining(), 7);
    assert_eq!(allowed.retry_after(), None);

    let denied = RateLimitDecision::denied(Duration::from_secs(3));
    assert!(!denied.is_allowed());
    assert_eq!(denied.remaining(), 0);
    assert_eq!(denied.retry_after(), Some(Duration::from_secs(3)));
}

#[test]
fn rate_limit_errors_are_classified() {
    use std::error::Error;

    assert_eq!(
        RateLimitError::LockPoisoned.error_kind(),
        ErrorKind::Internal
    );
    assert!(!RateLimitError::LockPoisoned.error_descriptor().retryable());
    assert!(
        RateLimitError::CapacityExceeded
            .error_descriptor()
            .retryable()
    );
    let secret = "redis://user:private-password@internal-host";
    let error = RateLimitError::Store(std::io::Error::other(secret).into());
    assert_eq!(
        RateLimitError::InvalidCapacity.error_kind(),
        ErrorKind::Validation
    );
    assert_eq!(error.error_kind(), ErrorKind::Unavailable);
    assert!(error.error_descriptor().retryable());
    assert_eq!(error.error_code(), "rate_limit_store_unavailable");
    assert_eq!(error.source().unwrap().to_string(), secret);
    assert!(
        error
            .source()
            .unwrap()
            .downcast_ref::<std::io::Error>()
            .is_some()
    );
    assert!(!error.to_string().contains(secret));
    assert!(!format!("{error:?}").contains(secret));
}
#[test]
fn principal_keys_isolate_tenants_kinds_and_identifiers() {
    use crate::{auth::Principal, http::RequestContext};
    let key = |principal| {
        let mut request = axum::http::Request::new(());
        let context = RequestContext::from_headers(request.headers()).with_principal(principal);
        request.extensions_mut().insert(context);
        super::RateLimitKeySource::Principal
            .key_for(&request)
            .unwrap()
    };
    let principals = [
        Principal::user("42").unwrap(),
        Principal::client("42").unwrap(),
        Principal::service_account("42").unwrap(),
        Principal::user("42")
            .unwrap()
            .with_tenant_id("tenant-a")
            .unwrap(),
        Principal::user("42")
            .unwrap()
            .with_tenant_id("tenant-b")
            .unwrap(),
        Principal::user("43").unwrap(),
    ];
    let keys: std::collections::HashSet<_> = principals.iter().cloned().map(key).collect();
    assert_eq!(keys.len(), principals.len());
    assert_eq!(key(principals[0].clone()), key(principals[0].clone()));
    assert!(
        keys.iter()
            .all(|key| key.starts_with("principal:") && !key.contains("tenant-"))
    );
}

#[tokio::test]
async fn tenant_keys_share_capacity_across_identities_and_reject_missing_tenants() {
    use crate::{
        auth::Principal,
        http::{IdempotencyScope, VerifiedAuthentication},
    };

    let runtime = RateLimitRuntime::in_memory(
        RateLimitConfig::new(1, 1, Duration::from_secs(3600)).unwrap(),
        RateLimitKeySource::Tenant,
    );
    let request = |principal: Principal| {
        let mut request = Request::new(());
        VerifiedAuthentication::new(principal, IdempotencyScope::new("test")).install(&mut request);
        request
    };
    let tenant_a_user = request(
        Principal::user("alice")
            .unwrap()
            .with_tenant_id("tenant-a")
            .unwrap(),
    );
    let tenant_a_client = request(
        Principal::client("automation")
            .unwrap()
            .with_tenant_id("tenant-a")
            .unwrap(),
    );
    let tenant_b = request(
        Principal::user("alice")
            .unwrap()
            .with_tenant_id("tenant-b")
            .unwrap(),
    );
    let tenant_a_key = RateLimitKeySource::Tenant.key_for(&tenant_a_user).unwrap();
    assert_eq!(
        RateLimitKeySource::Tenant.key_for(&tenant_a_client),
        Some(tenant_a_key.clone())
    );
    assert!(!tenant_a_key.contains("tenant-a"));
    assert_ne!(
        RateLimitKeySource::Principal.key_for(&tenant_a_user),
        Some(tenant_a_key)
    );
    assert!(enforce_rate_limit(&runtime, &tenant_a_user).await.is_ok());
    assert!(matches!(
        enforce_rate_limit(&runtime, &tenant_a_client).await,
        Err(RateLimitRejection::Limited { .. })
    ));
    assert!(enforce_rate_limit(&runtime, &tenant_b).await.is_ok());

    for missing in [
        request(Principal::user("tenantless").unwrap()),
        Request::builder()
            .header("x-tenant-id", "tenant-a")
            .body(())
            .unwrap(),
    ] {
        assert_eq!(
            enforce_rate_limit(&runtime, &missing).await,
            Err(RateLimitRejection::MissingKey)
        );
    }
}