guard-core-engine 4.4.0

Detection engine for the Guard ecosystem: pattern compilation, input preprocessing, and semantic analysis.
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
871
872
873
//! The client-IP extraction from the forwarded chain: the reference
//! `_utils/ip_extraction.py`'s depth-limited `X-Forwarded-For` walk, driven
//! by the `trusted_proxies` / `trusted_proxy_depth` knobs.
//!
//! Semantics, mirroring `_resolve_client_ip_from_forwarded_chain` exactly:
//!
//! ```text
//! no header:                        the connecting peer is the client
//! chain shorter than the depth:     the connecting peer (warn once)
//! right side holds unlisted peers:  walk right to left, skip trusted
//!                                   entries, first untrusted wins (warn)
//! otherwise:                        the entry `depth` from the right,
//!                                   port-stripped and canonicalized
//! ```
//!
//! A selected entry that is itself on the trusted list surfaces the
//! over-declared-depth warning as data ([`ChainWarnings`]) - the engine
//! has no logger, so the once-only warnings ride the result for the
//! caller to log. Unparseable entries and metacharacter candidates
//! (`*?[]\`) resolve back to the connecting peer, never to a spoof.
//!
//! # Example
//!
//! ```
//! use guard_core_engine::ip_extraction::{extract_client_ip, ClientIpSource};
//!
//! // A trusted proxy's claim is honored one hop deep.
//! let extraction = extract_client_ip(
//!     Some("10.0.0.1"),
//!     Some("203.0.113.7"),
//!     &["10.0.0.0/8".to_owned()],
//!     1,
//! );
//! assert_eq!(extraction.client_ip, "203.0.113.7");
//! assert_eq!(extraction.source, ClientIpSource::ForwardedChain);
//!
//! // An untrusted peer's header is ignored (the spoof signal rides along).
//! let extraction = extract_client_ip(
//!     Some("192.0.2.9"),
//!     Some("203.0.113.7"),
//!     &["10.0.0.0/8".to_owned()],
//!     1,
//! );
//! assert_eq!(extraction.client_ip, "192.0.2.9");
//! assert!(extraction.untrusted_forwarded_header);
//!
//! // No trusted proxies at all: the header never decides.
//! let extraction = extract_client_ip(Some("192.0.2.9"), Some("203.0.113.7"), &[], 1);
//! assert_eq!(extraction.client_ip, "192.0.2.9");
//! assert_eq!(extraction.source, ClientIpSource::Connecting);
//! ```

use std::net::IpAddr;
use std::str::FromStr;

use crate::ip_gate::IpNet;

/// The reference `UNKNOWN_CLIENT_IDENTITY`: the identity a request with no
/// connecting peer carries.
pub const UNKNOWN_CLIENT_IDENTITY: &str = "unknown";

/// Where the extracted client identity came from (the reference
/// `extract_client_ip`'s arms).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClientIpSource {
    /// The connecting peer itself (not a trusted proxy, or nothing to walk).
    Connecting,
    /// Resolved from the `X-Forwarded-For` chain at the declared depth.
    ForwardedChain,
    /// No connecting peer at all (the `unknown` identity, or the `unix`
    /// proxy arm walking from unknown).
    Unknown,
}

/// The once-only warnings the reference logs, surfaced as data (the engine
/// has no logger; the caller logs and de-duplicates).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ChainWarnings {
    /// The chain had fewer entries than `trusted_proxy_depth` (the
    /// reference `_warn_forwarded_header_chain_too_short`).
    pub chain_too_short: bool,
    /// The declared depth over-counts the real hops: `Some(count)` of
    /// right-side entries are not on the trusted list (the reference
    /// `_warn_forwarded_header_depth_overcounts_hops`).
    pub depth_overcounts: Option<usize>,
    /// The selected entry is itself a trusted proxy (the reference
    /// `_warn_forwarded_header_selected_entry_trusted_proxy`).
    pub selected_entry_trusted: bool,
}

/// One extraction: the identity plus where it came from and what the
/// caller should log.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientIpExtraction {
    /// The resolved client identity (`UNKNOWN_CLIENT_IDENTITY` when the
    /// request has no peer and the `unix` arm does not apply).
    pub client_ip: String,
    /// Which arm produced the identity.
    pub source: ClientIpSource,
    /// An untrusted peer sent an `X-Forwarded-For` header (the reference's
    /// spoof-attempt signal: the header is ignored, the event is the
    /// caller's to emit).
    pub untrusted_forwarded_header: bool,
    /// The chain-walk warnings (empty unless [`ClientIpSource::
    /// ForwardedChain`] or the too-short arm ran).
    pub warnings: ChainWarnings,
}

/// `_strip_ip_brackets`.
#[must_use]
fn strip_ip_brackets(value: &str) -> &str {
    value
        .strip_prefix('[')
        .and_then(|rest| rest.strip_suffix(']'))
        .unwrap_or(value)
}

/// `_strip_forwarded_entry_port`: `[v6]:port` and `host:port` lose the
/// port; anything else passes through untouched.
#[must_use]
pub fn strip_forwarded_entry_port(value: &str) -> &str {
    if let Some(rest) = value.strip_prefix('[') {
        let Some(closing) = rest.find(']') else {
            return value;
        };
        let remainder = &rest[closing + 1..];
        let port_form = remainder.len() > 1
            && remainder.starts_with(':')
            && remainder[1..].chars().all(|c| c.is_ascii_digit());
        if remainder.is_empty() || port_form {
            return &rest[..closing];
        }
        return value;
    }
    match value.split_once(':') {
        Some((host, port))
            if !host.contains(':')
                && !port.is_empty()
                && port.chars().all(|c| c.is_ascii_digit()) =>
        {
            host
        }
        _ => value,
    }
}

/// An address literal as the reference `ip_address` reads it: the address,
/// plus the IPv6 zone identifier when the literal carries one (`fe80::1%eth0`).
/// `std` parses no zones, so the zone is split off here.
fn parse_ip_literal(value: &str) -> Option<(IpAddr, Option<&str>)> {
    match value.split_once('%') {
        Some((address, zone)) if !zone.is_empty() && address.contains(':') => {
            let addr = IpAddr::from_str(address).ok()?;
            addr.is_ipv6().then_some((addr, Some(zone)))
        }
        Some(_) => None,
        None => IpAddr::from_str(value).ok().map(|addr| (addr, None)),
    }
}

/// `_canonical_ip_text` over a parsed literal: an IPv4-mapped address
/// collapses to its IPv4 text unless it carries a zone (the reference keeps
/// the zoned spelling distinct).
fn literal_text(addr: IpAddr, zone: Option<&str>) -> String {
    zone.map_or_else(|| canonical_ip_text(addr), |zone| format!("{addr}%{zone}"))
}

/// `_canonicalize_ip`: canonical text for a parseable address (an
/// IPv4-mapped IPv6 collapses to its IPv4 text), the raw value otherwise.
#[must_use]
pub fn canonicalize_ip(value: &str) -> String {
    parse_ip_literal(strip_ip_brackets(value))
        .map_or_else(|| value.to_owned(), |(addr, zone)| literal_text(addr, zone))
}

/// `_canonical_ip_text`.
#[must_use]
pub fn canonical_ip_text(addr: IpAddr) -> String {
    match addr {
        IpAddr::V6(v6) => v6
            .to_ipv4_mapped()
            .map_or_else(|| v6.to_string(), |mapped| mapped.to_string()),
        IpAddr::V4(v4) => v4.to_string(),
    }
}

/// `_forwarded_header_candidate_has_metachar`.
#[must_use]
pub fn candidate_has_metachar(candidate: &str) -> bool {
    candidate
        .chars()
        .any(|c| matches!(c, '*' | '?' | '[' | ']' | '\\'))
}

/// `_forwarded_header_ips`: the entries, comma-split, port-stripped.
#[must_use]
pub fn forwarded_header_ips(forwarded_for: &str) -> Vec<String> {
    forwarded_for
        .split(',')
        .map(|entry| strip_forwarded_entry_port(entry.trim()).to_owned())
        .collect()
}

/// `_proxy_matches` / `_is_trusted_proxy`.
///
/// The connecting text must parse as an address; a bare entry then compares
/// as text (the `unix` token never matches a real peer, and an IPv4-mapped
/// spelling is a different text from its IPv4 form), a CIDR entry contains
/// the address within its own family.
#[must_use]
pub fn is_trusted_proxy(connecting: &str, trusted_proxies: &[String]) -> bool {
    let Some((addr, _zone)) = parse_ip_literal(connecting) else {
        return false;
    };
    trusted_proxies.iter().any(|proxy| {
        if proxy.contains('/') {
            IpNet::parse(proxy).is_some_and(|network| network.contains(addr))
        } else {
            connecting == proxy
        }
    })
}

/// `_forwarded_header_candidate_addr`: the parsed candidate and its text.
#[must_use]
fn candidate_addr(candidate: &str) -> Option<(IpAddr, Option<&str>)> {
    parse_ip_literal(candidate)
}

/// `_forwarded_header_right_side_unlisted_count`.
#[must_use]
fn right_side_unlisted_count(
    ips: &[String],
    proxy_depth: u32,
    trusted_proxies: &[String],
) -> usize {
    let depth = usize::try_from(proxy_depth).unwrap_or(ips.len());
    let start = ips.len().saturating_sub(depth.saturating_sub(1));
    ips[start..]
        .iter()
        .filter(|entry| !is_trusted_proxy(&canonicalize_ip(entry), trusted_proxies))
        .count()
}

/// `_resolve_forwarded_chain_right_to_left`: the first untrusted entry
/// from the right, `None` when only trusted entries remain or a candidate
/// is unparseable or carries a metacharacter.
#[must_use]
fn resolve_chain_right_to_left(ips: &[String], trusted_proxies: &[String]) -> Option<String> {
    ips.iter()
        .rev()
        .find(|entry| !is_trusted_proxy(&canonicalize_ip(entry), trusted_proxies))
        .and_then(|entry| {
            // Metachar first: a metachar candidate never parses as an
            // address, so the reference's parse-then-metachar pair has
            // this exact truth table (the reference keeps the order only
            // for readability).
            if candidate_has_metachar(entry) {
                return None;
            }
            candidate_addr(entry).map(|_| canonicalize_ip(entry))
        })
}

/// `_resolve_client_ip_from_forwarded_chain`: the depth-limited walk with
/// the warnings as data. Failures and short chains degrade to the
/// connecting identity, never to a header claim.
#[must_use]
pub fn resolve_client_ip_from_forwarded_chain(
    canonical_connecting: &str,
    forwarded_for: Option<&str>,
    proxy_depth: u32,
    trusted_proxies: &[String],
) -> ClientIpExtraction {
    let mut warnings = ChainWarnings::default();
    let Some(forwarded_for) = forwarded_for.filter(|value| !value.is_empty()) else {
        return ClientIpExtraction {
            client_ip: canonical_connecting.to_owned(),
            source: ClientIpSource::Connecting,
            untrusted_forwarded_header: false,
            warnings,
        };
    };

    let ips = forwarded_header_ips(forwarded_for);
    let chain_length = ips.len();

    let depth = usize::try_from(proxy_depth).unwrap_or(0);
    if depth == 0 || chain_length < depth {
        warnings.chain_too_short = true;
        return ClientIpExtraction {
            client_ip: canonical_connecting.to_owned(),
            source: ClientIpSource::Connecting,
            untrusted_forwarded_header: false,
            warnings,
        };
    }

    if !trusted_proxies.is_empty() {
        let unlisted = right_side_unlisted_count(&ips, proxy_depth, trusted_proxies);
        if unlisted > 0 {
            warnings.depth_overcounts = Some(unlisted);
            let Some(resolved) = resolve_chain_right_to_left(&ips, trusted_proxies) else {
                return ClientIpExtraction {
                    client_ip: canonical_connecting.to_owned(),
                    source: ClientIpSource::Connecting,
                    untrusted_forwarded_header: false,
                    warnings,
                };
            };
            return ClientIpExtraction {
                client_ip: resolved,
                source: ClientIpSource::ForwardedChain,
                untrusted_forwarded_header: false,
                warnings,
            };
        }
    }

    // The depth gate above guarantees an entry at `depth` from the right.
    let candidate = ips[chain_length - depth].as_str();
    // Metachar first: a metachar candidate never parses as an address, so
    // the reference's parse-then-metachar pair has this exact truth table.
    if candidate_has_metachar(candidate) || candidate_addr(candidate).is_none() {
        return ClientIpExtraction {
            client_ip: canonical_connecting.to_owned(),
            source: ClientIpSource::Connecting,
            untrusted_forwarded_header: false,
            warnings,
        };
    }

    let client_ip = canonicalize_ip(candidate);
    warnings.selected_entry_trusted = is_trusted_proxy(&client_ip, trusted_proxies);
    ClientIpExtraction {
        client_ip,
        source: ClientIpSource::ForwardedChain,
        untrusted_forwarded_header: false,
        warnings,
    }
}

/// `extract_client_ip`: the reference entry point. `client_host` is the
/// connecting peer (`None` for a socket connection); `forwarded_for` the
/// raw `X-Forwarded-For` header.
#[must_use]
pub fn extract_client_ip(
    client_host: Option<&str>,
    forwarded_for: Option<&str>,
    trusted_proxies: &[String],
    proxy_depth: u32,
) -> ClientIpExtraction {
    // An empty peer is no peer (the reference tests `not request.client_host`).
    let Some(client_host) = client_host.filter(|host| !host.is_empty()) else {
        // The socket arm: with `unix` on the proxy list the chain is still
        // walked, from the unknown identity (the reference `_handle` arm).
        if trusted_proxies.iter().any(|proxy| proxy == "unix") {
            let mut extraction = resolve_client_ip_from_forwarded_chain(
                UNKNOWN_CLIENT_IDENTITY,
                forwarded_for,
                proxy_depth,
                trusted_proxies,
            );
            if extraction.source == ClientIpSource::Connecting {
                UNKNOWN_CLIENT_IDENTITY.clone_into(&mut extraction.client_ip);
                extraction.source = ClientIpSource::Unknown;
            }
            return extraction;
        }
        return ClientIpExtraction {
            client_ip: UNKNOWN_CLIENT_IDENTITY.to_owned(),
            source: ClientIpSource::Unknown,
            untrusted_forwarded_header: false,
            warnings: ChainWarnings::default(),
        };
    };

    let canonical_connecting = canonicalize_ip(client_host);

    if trusted_proxies.is_empty() {
        // The preempted-header warning is the caller's (it rides the flag).
        return ClientIpExtraction {
            client_ip: canonical_connecting,
            source: ClientIpSource::Connecting,
            untrusted_forwarded_header: forwarded_for.is_some_and(|value| !value.is_empty()),
            warnings: ChainWarnings::default(),
        };
    }

    if !is_trusted_proxy(client_host, trusted_proxies) {
        return ClientIpExtraction {
            client_ip: canonical_connecting,
            source: ClientIpSource::Connecting,
            untrusted_forwarded_header: forwarded_for.is_some_and(|value| !value.is_empty()),
            warnings: ChainWarnings::default(),
        };
    }

    resolve_client_ip_from_forwarded_chain(
        &canonical_connecting,
        forwarded_for,
        proxy_depth,
        trusted_proxies,
    )
}

/// The status of the missing-client-address rejection (the reference
/// `BypassHandler.handle_passthrough` 403).
pub const UNRESOLVABLE_CLIENT_ADDRESS_STATUS: u16 = 403;

/// The body of the missing-client-address rejection.
pub const UNRESOLVABLE_CLIENT_ADDRESS_MESSAGE: &str = "Client address could not be determined";

/// The check name the rejection reports to the `on_block` hook
/// (`UNRESOLVABLE_CLIENT_ADDRESS_CHECK_NAME`).
pub const UNRESOLVABLE_CLIENT_ADDRESS_CHECK_NAME: &str = "client_address_unresolved";

/// One request's client resolution: the identity the pipeline runs under
/// and whether `fail_secure` rejects the request outright.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientResolution {
    /// The extraction behind the identity (source, spoof flag, warnings).
    pub extraction: ClientIpExtraction,
    /// The identity as an address; `None` for the `unknown` identity (the
    /// pipeline then runs unattributed, the reference's `"unknown"` run).
    pub ip: Option<IpAddr>,
    /// A peer-less request that resolves to `unknown` under `fail_secure`:
    /// answer 403 [`UNRESOLVABLE_CLIENT_ADDRESS_MESSAGE`] before any check
    /// (the reference `handle_passthrough`).
    pub reject: bool,
}

/// The reference client resolution an adapter runs per request.
///
/// `extract_client_ip` over the connecting `peer`, the raw
/// `X-Forwarded-For` header, `trusted_proxies` and `trusted_proxy_depth`,
/// plus the `handle_passthrough` rule for a request with no peer address
/// (`fail_secure` rejects it unless the `unix` proxy token lets the chain
/// resolve it).
///
/// # Example
///
/// ```
/// use guard_core_engine::ip_extraction::resolve_client;
///
/// // A peer-less request under fail_secure is rejected.
/// assert!(resolve_client(None, None, &[], 1, true).reject);
/// // A trusted proxy's chain decides the client.
/// let resolution = resolve_client(
///     Some("10.0.0.1".parse().unwrap()),
///     Some("203.0.113.7"),
///     &["10.0.0.0/8".to_owned()],
///     1,
///     true,
/// );
/// assert_eq!(resolution.ip, Some("203.0.113.7".parse().unwrap()));
/// ```
#[must_use]
pub fn resolve_client(
    peer: Option<IpAddr>,
    forwarded_for: Option<&str>,
    trusted_proxies: &[String],
    proxy_depth: u32,
    fail_secure: bool,
) -> ClientResolution {
    let peer_text = peer.map(|addr| addr.to_string());
    let extraction = extract_client_ip(
        peer_text.as_deref(),
        forwarded_for,
        trusted_proxies,
        proxy_depth,
    );
    let unknown = extraction.client_ip == UNKNOWN_CLIENT_IDENTITY;
    let ip = if unknown {
        None
    } else {
        // A zoned identity has no `IpAddr` form (the zone is part of the identity).
        parse_ip_literal(&extraction.client_ip)
            .and_then(|(addr, zone)| zone.is_none().then_some(addr))
    };
    ClientResolution {
        reject: peer.is_none() && unknown && fail_secure,
        extraction,
        ip,
    }
}

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

    fn proxies(entries: &[&str]) -> Vec<String> {
        entries.iter().map(ToString::to_string).collect()
    }

    #[test]
    fn the_depth_selects_the_entry_from_the_right() {
        // One appending proxy (depth 1): the client is the last entry.
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("203.0.113.7"),
            &proxies(&["10.0.0.0/8"]),
            1,
        );
        assert_eq!(extraction.client_ip, "203.0.113.7");
        assert_eq!(extraction.source, ClientIpSource::ForwardedChain);
        assert!(!extraction.warnings.selected_entry_trusted);

        // Two appending proxies (depth 3, both hops trusted): the client
        // is third from the right.
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("203.0.113.7, 198.51.100.4, 10.0.0.1"),
            &proxies(&["10.0.0.0/8", "198.51.100.0/24"]),
            3,
        );
        assert_eq!(extraction.client_ip, "203.0.113.7");

        // A depth that lands on a trusted entry still answers it, with
        // the over-declared-depth warning (the reference warns and
        // returns the selected entry).
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("203.0.113.7, 10.0.0.1"),
            &proxies(&["10.0.0.0/8"]),
            1,
        );
        assert_eq!(extraction.client_ip, "10.0.0.1");
        assert!(extraction.warnings.selected_entry_trusted);
    }

    #[test]
    fn a_short_chain_falls_back_to_the_connecting_peer() {
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("203.0.113.7"),
            &proxies(&["10.0.0.0/8"]),
            3,
        );
        assert_eq!(extraction.client_ip, "10.0.0.1");
        assert_eq!(extraction.source, ClientIpSource::Connecting);
        assert!(extraction.warnings.chain_too_short);
    }

    #[test]
    fn an_over_counting_depth_walks_right_to_left() {
        // The declared depth counts a hop the trusted list does not
        // cover: an entry to the right of the selection is unlisted, the
        // walk skips trusted entries and answers the first untrusted one.
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("203.0.113.7, 198.51.100.4, 10.0.0.1"),
            &proxies(&["10.0.0.0/8"]),
            3,
        );
        assert_eq!(extraction.client_ip, "198.51.100.4");
        assert_eq!(extraction.warnings.depth_overcounts, Some(1));

        // A depth whose right side is fully trusted never walks.
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("10.0.0.2, 10.0.0.1"),
            &proxies(&["10.0.0.0/8"]),
            1,
        );
        assert_eq!(extraction.client_ip, "10.0.0.1");
        assert_eq!(extraction.source, ClientIpSource::ForwardedChain);
        assert_eq!(extraction.warnings.depth_overcounts, None);
    }

    #[test]
    fn unparseable_and_metachar_candidates_degrade_to_connecting() {
        // The depth-selected entry is unparseable: connecting wins.
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("not-an-ip"),
            &proxies(&["10.0.0.0/8"]),
            1,
        );
        assert_eq!(extraction.client_ip, "10.0.0.1");

        // The depth-selected entry carries a metacharacter: connecting.
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("*.evil.example"),
            &proxies(&["10.0.0.0/8"]),
            1,
        );
        assert_eq!(extraction.client_ip, "10.0.0.1");

        // The right-to-left walk refuses a metachar candidate too: the
        // rightmost untrusted entry is malformed, so the walk has no
        // answer and the connecting identity stands.
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("203.0.113.7, *.evil.example, 10.0.0.1"),
            &proxies(&["10.0.0.0/8"]),
            3,
        );
        assert_eq!(extraction.client_ip, "10.0.0.1");
        assert_eq!(extraction.warnings.depth_overcounts, Some(1));
    }

    #[test]
    fn a_selected_trusted_entry_warns() {
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("10.0.0.9, 10.0.0.1"),
            &proxies(&["10.0.0.0/8"]),
            2,
        );
        assert_eq!(extraction.client_ip, "10.0.0.9");
        assert!(extraction.warnings.selected_entry_trusted);
    }

    #[test]
    fn untrusted_peers_and_absent_proxies_ignore_the_header() {
        let extraction = extract_client_ip(
            Some("192.0.2.9"),
            Some("203.0.113.7"),
            &proxies(&["10.0.0.0/8"]),
            1,
        );
        assert_eq!(extraction.client_ip, "192.0.2.9");
        assert_eq!(extraction.source, ClientIpSource::Connecting);
        assert!(extraction.untrusted_forwarded_header);

        let extraction = extract_client_ip(Some("192.0.2.9"), Some("203.0.113.7"), &[], 1);
        assert_eq!(extraction.client_ip, "192.0.2.9");
        assert!(extraction.untrusted_forwarded_header);

        // No header at all: no spoof signal.
        let extraction = extract_client_ip(Some("192.0.2.9"), None, &proxies(&["10.0.0.0/8"]), 1);
        assert!(!extraction.untrusted_forwarded_header);
    }

    #[test]
    fn canonicalization_strips_brackets_ports_and_v4_mapping() {
        assert_eq!(
            strip_forwarded_entry_port("[2001:db8::1]:443"),
            "2001:db8::1"
        );
        assert_eq!(strip_forwarded_entry_port("2001:db8::1"), "2001:db8::1");
        assert_eq!(
            strip_forwarded_entry_port("203.0.113.7:8443"),
            "203.0.113.7"
        );
        assert_eq!(strip_forwarded_entry_port("203.0.113.7"), "203.0.113.7");
        // A bare v6 with one colon-free host:port shape stays intact.
        assert_eq!(strip_forwarded_entry_port("2001:db8::1"), "2001:db8::1");
        assert_eq!(canonicalize_ip("[2001:db8::1]"), "2001:db8::1");
        assert_eq!(canonicalize_ip("::ffff:203.0.113.7"), "203.0.113.7");
        assert_eq!(canonicalize_ip("not-an-ip"), "not-an-ip");
    }

    #[test]
    fn the_unknown_arm_walks_only_for_unix_proxies() {
        let extraction = extract_client_ip(None, Some("203.0.113.7"), &proxies(&["unix"]), 1);
        assert_eq!(extraction.client_ip, "203.0.113.7");
        assert_eq!(extraction.source, ClientIpSource::ForwardedChain);

        let extraction = extract_client_ip(None, Some("203.0.113.7"), &[], 1);
        assert_eq!(extraction.client_ip, UNKNOWN_CLIENT_IDENTITY);
        assert_eq!(extraction.source, ClientIpSource::Unknown);

        // The unix walk degrading to connecting reports the unknown identity.
        let extraction = extract_client_ip(None, None, &proxies(&["unix"]), 1);
        assert_eq!(extraction.client_ip, UNKNOWN_CLIENT_IDENTITY);
        assert_eq!(extraction.source, ClientIpSource::Unknown);
    }

    #[test]
    fn malformed_bracket_entries_pass_through_untouched() {
        // An unterminated bracket form is not an address.
        assert_eq!(strip_forwarded_entry_port("[2001:db8::1"), "[2001:db8::1");
        // A bracket form with trailing junk past the closing bracket is
        // not `host]:port` either.
        assert_eq!(
            strip_forwarded_entry_port("[2001:db8::1]junk"),
            "[2001:db8::1]junk"
        );
        // The clean forms still strip.
        assert_eq!(strip_forwarded_entry_port("[2001:db8::1]"), "2001:db8::1");
        assert_eq!(
            strip_forwarded_entry_port("[2001:db8::1]:443"),
            "2001:db8::1"
        );
    }

    #[test]
    fn an_empty_trusted_list_still_walks_at_the_declared_depth() {
        // Direct resolve with no proxy list: the depth arm answers the
        // entry (the caller decided trust before calling).
        let extraction =
            resolve_client_ip_from_forwarded_chain("10.0.0.1", Some("203.0.113.7"), 1, &[]);
        assert_eq!(extraction.client_ip, "203.0.113.7");
        assert_eq!(extraction.source, ClientIpSource::ForwardedChain);
        assert_eq!(extraction.warnings, ChainWarnings::default());
    }

    #[test]
    fn an_unparseable_rightmost_untrusted_entry_ends_the_walk() {
        // The rightmost untrusted entry does not parse: the walk has no
        // answer and the connecting identity stands.
        let extraction = extract_client_ip(
            Some("10.0.0.1"),
            Some("203.0.113.7, not-an-ip, 10.0.0.1"),
            &proxies(&["10.0.0.0/8"]),
            3,
        );
        assert_eq!(extraction.client_ip, "10.0.0.1");
        assert_eq!(extraction.warnings.depth_overcounts, Some(1));
    }

    #[test]
    fn the_unix_token_never_matches_a_real_peer() {
        assert!(!is_trusted_proxy("127.0.0.1", &proxies(&["unix"])));
        assert!(is_trusted_proxy(
            "10.1.2.3",
            &proxies(&["unix", "10.0.0.0/8"])
        ));
        assert!(is_trusted_proxy("10.1.2.3", &proxies(&["10.1.2.3"])));
    }

    /// `(peer, X-Forwarded-For, trusted_proxies, depth, identity)`, recorded
    /// from the reference `extract_client_ip`.
    #[allow(clippy::type_complexity)]
    const REFERENCE: &[(Option<&str>, Option<&str>, &[&str], u32, &str)] = &[
        (
            Some("::ffff:10.0.0.1"),
            Some("203.0.113.7"),
            &["10.0.0.0/8"],
            1,
            "10.0.0.1",
        ),
        (
            Some("::ffff:10.0.0.1"),
            Some("203.0.113.7"),
            &["10.0.0.1"],
            1,
            "10.0.0.1",
        ),
        (
            Some("10.0.0.1"),
            Some("203.0.113.7"),
            &["10.0.0.0/8"],
            1,
            "203.0.113.7",
        ),
        (
            Some("::FFFF:10.0.0.1"),
            Some("203.0.113.7"),
            &[],
            1,
            "10.0.0.1",
        ),
        (Some("FE80::1%eth0"), None, &[], 1, "fe80::1%eth0"),
        (Some("fe80::1%eth0"), None, &[], 1, "fe80::1%eth0"),
        (Some("2001:DB8::1"), None, &[], 1, "2001:db8::1"),
        (
            Some("10.0.0.1"),
            Some("[2001:db8::1]:443"),
            &["10.0.0.1"],
            1,
            "2001:db8::1",
        ),
        (None, Some("203.0.113.7"), &["unix"], 1, "203.0.113.7"),
        (None, Some("203.0.113.7"), &[], 1, "unknown"),
        (None, None, &["unix"], 1, "unknown"),
        (Some(""), Some("203.0.113.7"), &["unix"], 1, "203.0.113.7"),
        (Some("not-an-ip"), None, &[], 1, "not-an-ip"),
        (
            Some("10.0.0.1"),
            Some("1.1.1.1, 203.0.113.7"),
            &["10.0.0.1"],
            2,
            "203.0.113.7",
        ),
        (
            Some("10.0.0.1"),
            Some("203.0.113.7"),
            &["10.0.0.1"],
            3,
            "10.0.0.1",
        ),
        (Some("::1"), Some("203.0.113.7"), &["::1"], 1, "203.0.113.7"),
        (
            Some("0:0:0:0:0:ffff:a00:1"),
            Some("9.9.9.9"),
            &["10.0.0.1"],
            1,
            "10.0.0.1",
        ),
    ];

    #[test]
    fn identities_follow_the_reference_table() {
        for (index, (peer, forwarded, proxy_list, depth, expected)) in REFERENCE.iter().enumerate()
        {
            let extraction = extract_client_ip(*peer, *forwarded, &proxies(proxy_list), *depth);
            assert_eq!(extraction.client_ip, *expected, "reference row {index}");
        }
    }

    #[test]
    fn a_peerless_request_is_rejected_only_when_unresolved_and_fail_secure() {
        let rejected = resolve_client(None, Some("203.0.113.7"), &[], 1, true);
        assert!(rejected.reject);
        assert_eq!(rejected.ip, None);
        assert_eq!(rejected.extraction.source, ClientIpSource::Unknown);

        let open = resolve_client(None, Some("203.0.113.7"), &[], 1, false);
        assert!(!open.reject);
        assert_eq!(open.ip, None);

        let unix = resolve_client(None, Some("203.0.113.7"), &proxies(&["unix"]), 1, true);
        assert!(!unix.reject);
        assert_eq!(unix.ip, Some("203.0.113.7".parse().unwrap()));
    }

    #[test]
    fn a_peer_resolves_through_the_trusted_chain_and_never_rejects() {
        let resolution = resolve_client(
            Some("10.0.0.1".parse().unwrap()),
            Some("203.0.113.7"),
            &proxies(&["10.0.0.0/8"]),
            1,
            true,
        );
        assert!(!resolution.reject);
        assert_eq!(resolution.ip, Some("203.0.113.7".parse().unwrap()));

        let untrusted = resolve_client(
            Some("192.0.2.9".parse().unwrap()),
            Some("203.0.113.7"),
            &proxies(&["10.0.0.0/8"]),
            1,
            true,
        );
        assert_eq!(untrusted.ip, Some("192.0.2.9".parse().unwrap()));
        assert!(untrusted.extraction.untrusted_forwarded_header);

        // An IPv4-mapped peer canonicalizes to its IPv4 identity.
        let mapped = resolve_client(
            Some("::ffff:192.0.2.9".parse().unwrap()),
            None,
            &[],
            1,
            true,
        );
        assert_eq!(mapped.ip, Some("192.0.2.9".parse().unwrap()));
    }

    #[test]
    fn a_zoned_chain_entry_keeps_its_text_but_has_no_address() {
        let resolution = resolve_client(None, Some("fe80::1%eth0"), &proxies(&["unix"]), 1, true);
        assert_eq!(resolution.extraction.client_ip, "fe80::1%eth0");
        assert_eq!(resolution.ip, None);
        assert!(!resolution.reject);
    }

    #[test]
    fn a_malformed_zone_literal_is_not_an_address() {
        // A zone on an IPv4 literal, an empty zone, and a non-address with a
        // zone-shaped tail all pass through as raw text and never trust.
        for raw in ["1.2.3.4%eth0", "fe80::1%", "not:an:ip%eth0"] {
            assert_eq!(canonicalize_ip(raw), raw);
            assert!(!is_trusted_proxy(raw, &proxies(&["fe80::/10", raw])));
        }
        // A well-formed zoned literal is an address and matches its network.
        assert!(is_trusted_proxy("fe80::1%eth0", &proxies(&["fe80::/10"])));
    }
}