nitr-http 0.0.0-beta.7

The Nitr HTTP server layer: hyper server, configuration, and the request/response Lua bridge.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// This file is part of Nitr.
// See https://nitrweb.com/ for more information
// Copyright (C) 2024-present Jose Quintana <joseluisq.net>

//! Rust-side protection enforced before a request reaches Lua: rate
//! limiting and request-size limits. These are infrastructure concerns —
//! implementing them in Lua would let the thing being protected against
//! consume the resources first.

use std::collections::HashMap;
use std::net::{IpAddr, Ipv6Addr};
use std::sync::Mutex;
use std::time::{Duration, Instant};

use hyper::StatusCode;

use crate::config::Config;
use crate::handler::{HttpResponse, rate_limited, rejection, wants_json};
use crate::request::LuaRequest;
use nitr_core::Result;

/// Above this many tracked client buckets, stale entries are purged — but
/// at most once per [`BUCKET_PURGE_INTERVAL`]. Purging on *every* check
/// past the threshold turned the limiter into an O(n) scan under the one
/// lock every connection serializes on: a client with a /64 (2^64 source
/// addresses) opened a bucket per request, none evictable inside the
/// window, and from ~10k buckets on every request in the server paid a
/// full-map walk.
const BUCKET_PURGE_THRESHOLD: usize = 10_000;

/// Minimum spacing between two purges.
const BUCKET_PURGE_INTERVAL: Duration = Duration::from_secs(1);

/// Hard cap on tracked clients (~20 MiB of buckets). Past it a client
/// not yet tracked is admitted *untracked* rather than refused: refusing
/// would let an address flood deny every new visitor, while admitting
/// costs nothing the flood could not already obtain by rotating
/// addresses. Clients already tracked keep their budget either way.
const MAX_BUCKETS: usize = 200_000;

/// Per-server protection state, shared by all connections.
#[derive(Debug)]
pub(crate) struct Protection {
    max_body_bytes: u64,
    max_uri_bytes: usize,
    trust_request_id: bool,
    dev_mode: bool,
    /// Per-read body progress budget; `None` when disabled.
    body_read: Option<Duration>,
    /// How long a request may wait for a Lua state before it is shed.
    pool_wait: Duration,
    rate: Option<RateLimiter>,
    /// Body-parsing bounds handed to each request.
    form: crate::request::FormLimits,
    /// The compiled `[cors]` policy; `None` when CORS is not configured.
    cors: Option<crate::cors::Cors>,
    /// The compiled `[compression]` policy.
    compression: crate::compress::Compression,
    /// `[headers]`, parsed once; validation refused anything that is not
    /// a header.
    response_headers: Vec<(hyper::header::HeaderName, hyper::header::HeaderValue)>,
    /// The OpenAPI document and page, swapped with the pool on reload.
    #[cfg(feature = "openapi")]
    docs: crate::openapi::docs::DocsSlot,
}

impl Protection {
    /// The current document and page, if any has been built.
    #[cfg(feature = "openapi")]
    pub(crate) fn docs(&self) -> Option<std::sync::Arc<crate::openapi::docs::OpenApiDocs>> {
        self.docs.read().ok().and_then(|slot| slot.clone())
    }

    /// The docs slot, for the server to fill once the pool exists and to
    /// swap on reload.
    #[cfg(feature = "openapi")]
    pub(crate) fn docs_slot(&self) -> crate::openapi::docs::DocsSlot {
        self.docs.clone()
    }

    pub(crate) fn new(cfg: &Config) -> Self {
        Self {
            max_body_bytes: cfg.limits.max_body_bytes,
            max_uri_bytes: cfg.limits.max_uri_bytes,
            trust_request_id: cfg.trust_request_id,
            dev_mode: cfg.dev_mode,
            body_read: match cfg.limits.body_read_ms {
                0 => None,
                ms => Some(Duration::from_millis(ms)),
            },
            pool_wait: Duration::from_millis(cfg.limits.pool_wait_ms),
            rate: cfg.rate_limit.enabled.then(|| {
                RateLimiter::new(
                    cfg.rate_limit.requests,
                    Duration::from_secs(cfg.rate_limit.window),
                    cfg.rate_limit.trust_forwarded_for,
                )
            }),
            form: crate::request::FormLimits {
                max_parts: cfg.limits.max_form_parts.max(1),
                max_field_bytes: cfg.limits.max_field_bytes,
                max_file_bytes: cfg.limits.max_file_bytes,
                upload_root: cfg.multipart.upload_dir.clone().map(std::sync::Arc::new),
            },
            cors: crate::cors::Cors::new(&cfg.cors),
            compression: crate::compress::Compression::new(&cfg.compression),
            response_headers: cfg
                .headers
                .iter()
                .filter_map(|(name, value)| {
                    Some((
                        hyper::header::HeaderName::from_bytes(name.as_bytes()).ok()?,
                        hyper::header::HeaderValue::from_str(value).ok()?,
                    ))
                })
                .collect(),
            #[cfg(feature = "openapi")]
            docs: std::sync::Arc::new(std::sync::RwLock::new(None)),
        }
    }

    /// The compiled CORS policy, or `None` when CORS is not configured.
    pub(crate) fn cors(&self) -> Option<&crate::cors::Cors> {
        self.cors.as_ref()
    }

    /// The compiled compression policy.
    pub(crate) fn compression(&self) -> &crate::compress::Compression {
        &self.compression
    }

    /// Adds the `[headers]` entries the response does not already carry.
    pub(crate) fn apply_headers(&self, headers: &mut hyper::HeaderMap) {
        for (name, value) in &self.response_headers {
            headers.entry(name).or_insert_with(|| value.clone());
        }
    }

    /// Body-parsing bounds handed to each request.
    pub(crate) fn form_limits(&self) -> crate::request::FormLimits {
        self.form.clone()
    }

    /// Whether error responses may carry internal detail.
    pub(crate) fn dev_mode(&self) -> bool {
        self.dev_mode
    }

    /// The checkout wait budget; zero means wait indefinitely.
    pub(crate) fn pool_wait(&self) -> Duration {
        self.pool_wait
    }

    /// How long each body read may wait for the next bytes (`[limits]
    /// body_read_ms`); `None` when the bound is disabled.
    pub(crate) fn body_read_timeout(&self) -> Option<Duration> {
        self.body_read
    }

    /// The configured request body ceiling, enforced as the body is read.
    pub(crate) fn max_body_bytes(&self) -> u64 {
        self.max_body_bytes
    }

    /// The id for a request: a trusted, well-formed inbound `X-Request-ID`
    /// when configured, otherwise a fresh UUIDv7 (time-sortable).
    pub(crate) fn request_id(&self, req: &hyper::Request<hyper::body::Incoming>) -> String {
        self.request_id_for_parts(req.headers())
    }

    /// [`request_id`](Self::request_id) over bare headers (used by the
    /// in-process test client, whose body type differs).
    pub(crate) fn request_id_for_parts(&self, headers: &hyper::HeaderMap) -> String {
        if self.trust_request_id
            && let Some(id) = headers
                .get("x-request-id")
                .and_then(|v| v.to_str().ok())
                .filter(|v| {
                    !v.is_empty() && v.len() <= 64 && v.bytes().all(|b| b.is_ascii_graphic())
                })
        {
            return id.to_string();
        }
        uuid::Uuid::now_v7().to_string()
    }

    /// Runs the pre-Lua checks; `Some` is the rejection response.
    pub(crate) fn check(&self, req: &LuaRequest) -> Option<Result<HttpResponse>> {
        let wants_json = wants_json(req.req.headers());
        if let Some(rate) = &self.rate
            && let Err(retry_after) = rate.check(req)
        {
            tracing::debug!(peer = %req.peer_addr, "request rate limited");
            return Some(rate_limited(retry_after, wants_json));
        }

        if uri_len(req) > self.max_uri_bytes {
            return Some(rejection(
                StatusCode::URI_TOO_LONG,
                "URI_TOO_LONG",
                None,
                wants_json,
            ));
        }

        // More than one `Authorization` header is refused outright. The
        // Lua header table keeps one value per name (last wins), so a
        // handler — or `nitr.auth` — would see one credential while a
        // proxy in front may have authenticated on the other: proxy
        // desync and credential confusion in one shape. Joining, the way
        // `Cookie` is joined for the Lua table, is wrong here — a joined
        // cookie string is still a valid cookie string, but a joined
        // credential is a credential nobody sent. Refusal is the one
        // answer that cannot diverge from what anything in front saw.
        // It lives here, pre-Lua, because it must also cover handlers
        // that read `req.headers.authorization` themselves.
        if req
            .req
            .headers()
            .get_all(hyper::header::AUTHORIZATION)
            .iter()
            .nth(1)
            .is_some()
        {
            tracing::debug!(
                peer = %req.peer_addr,
                "request refused: more than one Authorization header"
            );
            return Some(rejection(
                StatusCode::BAD_REQUEST,
                "BAD_REQUEST",
                None,
                wants_json,
            ));
        }

        // Declared body size; a chunked body that lies is caught later by
        // the handler's byte-counting body guard, which answers 413.
        let declared = req
            .req
            .headers()
            .get(hyper::header::CONTENT_LENGTH)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<u64>().ok());
        if declared.is_some_and(|len| len > self.max_body_bytes) {
            return Some(rejection(
                StatusCode::PAYLOAD_TOO_LARGE,
                "PAYLOAD_TOO_LARGE",
                None,
                wants_json,
            ));
        }

        None
    }
}

fn uri_len(req: &LuaRequest) -> usize {
    let uri = req.req.uri();
    uri.path().len() + uri.query().map_or(0, |q| q.len() + 1)
}

/// A fixed-window request counter per client.
#[derive(Debug)]
pub(crate) struct RateLimiter {
    max: u32,
    window: Duration,
    trust_forwarded_for: bool,
    buckets: Mutex<Buckets>,
}

/// The tracked clients and when they were last purged.
#[derive(Debug)]
struct Buckets {
    map: HashMap<IpAddr, (Instant, u32)>,
    last_purge: Instant,
}

impl RateLimiter {
    pub(crate) fn new(max: u32, window: Duration, trust_forwarded_for: bool) -> Self {
        Self {
            max,
            window,
            trust_forwarded_for,
            buckets: Mutex::new(Buckets {
                map: HashMap::new(),
                last_purge: Instant::now(),
            }),
        }
    }

    /// Returns `Err(retry_after_seconds)` when the client exceeded its
    /// budget for the current window.
    pub(crate) fn check(&self, req: &LuaRequest) -> std::result::Result<(), u64> {
        // The standard library's clock, so `nitr.test.clock.advance` can
        // move a test past the window; the real monotonic clock otherwise.
        self.check_with(req, nitr_std::clock::now_instant)
    }

    /// [`check`](Self::check) at an explicit instant — the seam that lets
    /// tests drive window expiry and bucket eviction deterministically
    /// instead of sleeping against the real clock.
    #[cfg(test)]
    fn check_at(&self, req: &LuaRequest, now: Instant) -> std::result::Result<(), u64> {
        self.check_with(req, || now)
    }

    fn check_with(
        &self,
        req: &LuaRequest,
        clock: impl FnOnce() -> Instant,
    ) -> std::result::Result<(), u64> {
        let key = self.client_key(req);
        let mut buckets = match self.buckets.lock() {
            Ok(guard) => guard,
            // Poisoning is unreachable in practice (no panics while held);
            // failing open beats taking the server down.
            Err(_) => return Ok(()),
        };
        // Read under the lock, so the instants the buckets see only move
        // forward: two requests that read the clock before contending for
        // the lock could otherwise record their windows out of order.
        let now = clock();
        if buckets.map.len() > BUCKET_PURGE_THRESHOLD
            && now.duration_since(buckets.last_purge) >= BUCKET_PURGE_INTERVAL
        {
            let window = self.window;
            buckets
                .map
                .retain(|_, (start, _)| now.duration_since(*start) < window);
            buckets.last_purge = now;
        }
        if buckets.map.len() >= MAX_BUCKETS && !buckets.map.contains_key(&key) {
            tracing::debug!(
                peer = %req.peer_addr,
                "rate limiter at its client cap; admitting a new client untracked"
            );
            return Ok(());
        }
        let bucket = buckets.map.entry(key).or_insert((now, 0));
        // A window that starts after `now` starts over. With the clock read
        // under the lock that happens only when `nitr test` resets its clock
        // after a test that advanced it: a bucket stamped in that test's
        // future would otherwise saturate `duration_since` to zero and stay
        // open for the whole advance. A racing request cannot reach this
        // branch, so it cannot reset another request's count.
        if now
            .checked_duration_since(bucket.0)
            .is_none_or(|elapsed| elapsed >= self.window)
        {
            *bucket = (now, 0);
        }
        bucket.1 += 1;
        if bucket.1 > self.max {
            let elapsed = now.duration_since(bucket.0);
            let retry = self.window.saturating_sub(elapsed).as_secs().max(1);
            return Err(retry);
        }
        Ok(())
    }

    /// The address the budget is keyed by, reduced to a bucket key.
    ///
    /// Behind a trusted proxy the *last* `X-Forwarded-For` entry of the
    /// *last* header line is used — the one that proxy appended, i.e. the
    /// address it accepted the connection from. The first entry is
    /// whatever the client wrote: every mainstream proxy appends rather
    /// than overwrites, so keying by it let a client mint a fresh budget
    /// per request with one header. Some proxies (HAProxy's `option
    /// forwardfor`) append a whole new header *line* rather than extend
    /// the first one, so it is the last line that carries the proxy's
    /// word. A header that does not parse falls back to the peer address.
    fn client_key(&self, req: &LuaRequest) -> IpAddr {
        let ip = if self.trust_forwarded_for
            && let Some(ip) = req
                .req
                .headers()
                .get_all("x-forwarded-for")
                .iter()
                .next_back()
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.rsplit(',').next())
                .and_then(|v| v.trim().parse().ok())
        {
            ip
        } else {
            req.peer_addr.ip()
        };
        bucket_key(ip)
    }
}

/// Reduces an address to the granularity a budget is tracked at: IPv4 as
/// is (after unmapping `::ffff:a.b.c.d`), IPv6 by its /64 — the smallest
/// allocation a single subscriber holds, and 2^64 addresses otherwise.
fn bucket_key(ip: IpAddr) -> IpAddr {
    match ip.to_canonical() {
        IpAddr::V4(v4) => IpAddr::V4(v4),
        IpAddr::V6(v6) => {
            let s = v6.segments();
            IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], s[3], 0, 0, 0, 0))
        }
    }
}

#[cfg(test)]
mod tests {
    use hyper::header::HeaderValue;

    use super::*;
    use http_body_util::BodyExt as _;

    fn limiter(max: u32, window_ms: u64, trust_forwarded_for: bool) -> RateLimiter {
        RateLimiter::new(max, Duration::from_millis(window_ms), trust_forwarded_for)
    }

    fn request(peer: &str, forwarded_for: Option<&str>) -> LuaRequest {
        let mut builder = hyper::Request::builder().uri("/");
        if let Some(xff) = forwarded_for {
            builder = builder.header("x-forwarded-for", xff);
        }
        let req = builder
            .body(
                http_body_util::Empty::<hyper::body::Bytes>::new()
                    .map_err(|err| match err {})
                    .boxed(),
            )
            .expect("request");
        LuaRequest {
            cached_body: None,
            body_consumed: false,
            valid: None,
            spool_dir: None,
            peer_addr: format!("{peer}:1234").parse().expect("addr"),
            tls: false,
            req,
            params: Vec::new(),
            id: "test".into(),
            limits: Default::default(),
            cached_form: None,
            body_limit: u64::MAX,
        }
    }

    #[test]
    fn the_budget_applies_per_client_ip() {
        let limiter = limiter(2, 60_000, false);
        let a = request("10.0.0.1", None);
        let b = request("10.0.0.2", None);
        assert!(limiter.check(&a).is_ok());
        assert!(limiter.check(&a).is_ok());
        let retry = limiter.check(&a).expect_err("third request is over");
        assert!(retry >= 1, "Retry-After must be at least a second");
        // Another client's budget is untouched.
        assert!(limiter.check(&b).is_ok());
    }

    #[test]
    fn the_window_resets_the_budget() {
        // Driven through `check_at` with synthetic instants: the old
        // real-clock version (60 ms sleep against a 30 ms window) passed
        // or failed with the scheduler's mood on a loaded runner.
        let limiter = limiter(1, 30, false);
        let req = request("10.0.0.1", None);
        let t0 = Instant::now();
        assert!(limiter.check_at(&req, t0).is_ok());
        assert!(limiter.check_at(&req, t0).is_err(), "over budget in-window");
        // One instant short of the window boundary is still the old window.
        assert!(
            limiter
                .check_at(&req, t0 + Duration::from_millis(29))
                .is_err()
        );
        assert!(
            limiter
                .check_at(&req, t0 + Duration::from_millis(30))
                .is_ok(),
            "a new window starts fresh"
        );
    }

    /// A window that starts after `now` starts over: under `nitr test` the
    /// clock is reset after a test that advanced it, and a bucket stamped
    /// in that future used to saturate `duration_since` to zero — the
    /// client stayed throttled for the whole advance (a day, for a test
    /// that aged a session).
    #[test]
    fn a_window_from_the_future_starts_over() {
        let limiter = limiter(1, 60_000, false);
        let req = request("10.0.0.1", None);
        let now = Instant::now();
        let advanced = now + Duration::from_secs(86_400);
        assert!(limiter.check_at(&req, advanced).is_ok());
        assert!(limiter.check_at(&req, advanced).is_err());
        assert!(
            limiter.check_at(&req, now).is_ok(),
            "back at the real clock, the future window is gone"
        );
        assert!(limiter.check_at(&req, now).is_err(), "and counting resumes");
    }

    /// The purge backstop (guard against unbounded `HashMap` growth from
    /// spoofed source IPs): once the map exceeds `BUCKET_PURGE_THRESHOLD`,
    /// the next check drops every bucket whose window has passed.
    #[test]
    fn stale_buckets_are_purged_past_the_threshold() {
        let limiter = limiter(100, 1_000, false);
        let t0 = Instant::now();

        // One bucket per distinct client IP, all opened at t0.
        for n in 0..=BUCKET_PURGE_THRESHOLD as u32 {
            let ip = format!("10.{}.{}.{}", n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff);
            assert!(limiter.check_at(&request(&ip, None), t0).is_ok());
        }
        assert!(
            limiter.buckets.lock().expect("buckets").map.len() > BUCKET_PURGE_THRESHOLD,
            "the map must actually be past the threshold for the purge to be tested"
        );

        // A later request finds the map oversized and evicts everything
        // stale; only itself (fresh) survives.
        let later = t0 + Duration::from_millis(1_500);
        assert!(
            limiter
                .check_at(&request("192.168.0.1", None), later)
                .is_ok()
        );
        assert_eq!(
            limiter.buckets.lock().expect("buckets").map.len(),
            1,
            "stale buckets must be evicted, not accumulate forever"
        );
    }

    /// The purge is rate-limited itself: past the threshold, requests
    /// inside the same second must not each pay a full-map scan.
    #[test]
    fn purges_are_spaced_out_not_paid_per_request() {
        let limiter = limiter(100, 60_000, false);
        let t0 = Instant::now();
        for n in 0..=BUCKET_PURGE_THRESHOLD as u32 {
            let ip = format!("10.{}.{}.{}", n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff);
            assert!(limiter.check_at(&request(&ip, None), t0).is_ok());
        }
        // Wait out the first purge, which drops nothing (all in-window)
        // but stamps the time, then verify the next check within the
        // interval leaves the stamp alone.
        let t1 = t0 + BUCKET_PURGE_INTERVAL + Duration::from_millis(1);
        assert!(limiter.check_at(&request("192.168.0.1", None), t1).is_ok());
        let stamped = limiter.buckets.lock().expect("buckets").last_purge;
        assert!(
            limiter
                .check_at(&request("192.168.0.2", None), t1 + Duration::from_millis(1))
                .is_ok()
        );
        assert_eq!(
            limiter.buckets.lock().expect("buckets").last_purge,
            stamped,
            "a second purge inside the interval must not run"
        );
    }

    /// IPv6 is keyed by /64: one subscriber's whole allocation shares a
    /// budget, so rotating the host bits buys nothing.
    #[test]
    fn ipv6_clients_are_keyed_by_their_64() {
        let rl = limiter(1, 60_000, false);
        assert!(rl.check(&request("[2001:db8:1:2::1]", None)).is_ok());
        assert!(
            rl.check(&request("[2001:db8:1:2:ffff::9]", None)).is_err(),
            "the same /64 is the same client"
        );
        assert!(
            rl.check(&request("[2001:db8:1:3::1]", None)).is_ok(),
            "a different /64 is a different client"
        );
        // A v4-mapped address is its v4 self.
        assert_eq!(
            bucket_key("::ffff:10.0.0.1".parse().expect("ip")),
            "10.0.0.1".parse::<IpAddr>().expect("ip")
        );
    }

    /// The trusted-id validation edges (`len <= 64`, ASCII-graphic only,
    /// non-empty): everything outside the shape is *replaced* by a fresh
    /// UUID, never echoed — a proxy header is still attacker-influenced
    /// text headed for log pipelines.
    #[test]
    fn trusted_request_ids_validate_the_shape_edges() {
        let cfg = Config {
            trust_request_id: true,
            ..Default::default()
        };
        let protection = Protection::new(&cfg);
        let id_for = |value: &[u8]| {
            let mut headers = hyper::HeaderMap::new();
            headers.insert(
                "x-request-id",
                HeaderValue::from_bytes(value).expect("header value"),
            );
            protection.request_id_for_parts(&headers)
        };

        // In shape: passed through verbatim, including the 64-byte edge.
        assert_eq!(id_for(b"req-from-proxy-1"), "req-from-proxy-1");
        let at_cap = "a".repeat(64);
        assert_eq!(id_for(at_cap.as_bytes()), at_cap);

        // Out of shape: one past the cap, empty, whitespace, non-ASCII.
        let over_cap = "a".repeat(65).into_bytes();
        for bad in [&over_cap[..], b"", b"has space", "caf\u{e9}".as_bytes()] {
            let id = id_for(bad);
            assert_ne!(id.as_bytes(), bad, "{bad:?} must not be echoed");
            assert!(
                uuid::Uuid::parse_str(&id).is_ok(),
                "the replacement must be a generated UUID, got `{id}`"
            );
        }

        // And without trust, even a well-shaped id is replaced.
        let untrusted = Protection::new(&Config::default());
        let mut headers = hyper::HeaderMap::new();
        headers.insert("x-request-id", HeaderValue::from_static("req-1"));
        assert_ne!(untrusted.request_id_for_parts(&headers), "req-1");
    }

    #[test]
    fn forwarded_for_is_honored_only_when_trusted() {
        // Untrusted: the header is attacker-controlled, so the peer
        // address keys the budget and the spoofed IPs share one bucket.
        let rl = limiter(1, 60_000, false);
        assert!(rl.check(&request("10.0.0.9", Some("1.1.1.1"))).is_ok());
        assert!(
            rl.check(&request("10.0.0.9", Some("2.2.2.2"))).is_err(),
            "spoofing the header must not buy a fresh budget"
        );

        // Trusted (behind a proxy): the *last* entry — the one the proxy
        // appended — keys the budget; whatever the client wrote in front
        // of it changes nothing.
        let rl = limiter(1, 60_000, true);
        assert!(
            rl.check(&request("10.0.0.9", Some("1.1.1.1, 9.9.9.9")))
                .is_ok()
        );
        assert!(
            rl.check(&request("10.0.0.9", Some("2.2.2.2, 9.9.9.9")))
                .is_err(),
            "a spoofed first entry must not buy a fresh budget"
        );
        assert!(rl.check(&request("10.0.0.9", Some("9.9.9.9"))).is_err());
        assert!(
            rl.check(&request("10.0.0.9", Some("2.2.2.2"))).is_ok(),
            "a different client gets its own budget"
        );
        // A garbage header falls back to the peer address.
        assert!(rl.check(&request("10.0.0.9", Some("not-an-ip"))).is_ok());

        // A proxy that adds a second header *line* (HAProxy) leaves the
        // client's line first: the last line is the proxy's word.
        let rl = limiter(1, 60_000, true);
        let two_lines = |first: &str| {
            let mut req = request("10.0.0.9", Some(first));
            req.req
                .headers_mut()
                .append("x-forwarded-for", HeaderValue::from_static("9.9.9.9"));
            req
        };
        assert!(rl.check(&two_lines("1.1.1.1")).is_ok());
        assert!(
            rl.check(&two_lines("2.2.2.2")).is_err(),
            "a fresh first line must not buy a fresh budget"
        );
    }
}