hyperlane-plugin-ip-filter 23.3.0

A zero-allocation IP allowlist/denylist and anti-spoofing client IP extraction plugin for the Hyperlane framework with /8 radix-indexed CIDR lookup, IPv4-mapped IPv6 canonicalization, RFC 7239 Forwarded/X-Forwarded-For right-to-left proxy peeling, and prebuilt 403 wire responses.
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
use super::*;

/// Formats [`IpFilterError`] for display diagnostics.
impl Display for IpFilterError {
    /// Renders a human-readable CIDR parsing error message.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyCidr => f.write_str(ERR_EMPTY_CIDR),
            Self::InvalidIp(raw) => write!(f, "{ERR_INVALID_IP}: {raw}"),
            Self::InvalidPrefix(raw) => write!(f, "{ERR_INVALID_PREFIX}: {raw}"),
            Self::PrefixOutOfRange(len) => write!(f, "{ERR_PREFIX_OUT_OF_RANGE}: /{len}"),
        }
    }
}

/// Marks [`IpFilterError`] as a standard error type.
impl Error for IpFilterError {}

/// Inherent constructors and membership checks for [`IpNet`].
impl IpNet {
    /// Parses a single IP address or CIDR specification (for example `"10.0.0.0/8"`, `"192.168.1.5"`, `"::ffff:10.0.0.0/104"`).
    ///
    /// IPv4-mapped IPv6 addresses and subnets (`>= /96` inside `::ffff:0:0/96`) are canonicalized to IPv4.
    ///
    /// # Arguments
    ///
    /// - `&str` - IP or CIDR string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpFilterError>` - Canonicalized CIDR block or parse error.
    pub fn parse(spec: &str) -> Result<Self, IpFilterError> {
        let trimmed: &str = spec.trim();
        if trimmed.is_empty() {
            return Err(IpFilterError::EmptyCidr);
        }
        let (addr_part, prefix_part): (&str, Option<&str>) = match trimmed.split_once('/') {
            Some((addr, prefix)) => (addr.trim(), Some(prefix.trim())),
            None => (trimmed, None),
        };
        let ip: IpAddr = IpAddr::from_str(addr_part)
            .map_err(|_| IpFilterError::InvalidIp(addr_part.to_owned()))?;
        match ip {
            IpAddr::V4(v4) => {
                let prefix_len: u8 = match prefix_part {
                    Some(raw) => raw
                        .parse::<u8>()
                        .map_err(|_| IpFilterError::InvalidPrefix(raw.to_owned()))?,
                    None => IPV4_MAX_PREFIX,
                };
                if prefix_len > IPV4_MAX_PREFIX {
                    return Err(IpFilterError::PrefixOutOfRange(prefix_len));
                }
                let mask: u32 = ipv4_prefix_mask(prefix_len);
                let network: u32 = u32::from(v4) & mask;
                Ok(Self::V4 {
                    network,
                    mask,
                    prefix_len,
                })
            }
            IpAddr::V6(v6) => {
                let prefix_len: u8 = match prefix_part {
                    Some(raw) => raw
                        .parse::<u8>()
                        .map_err(|_| IpFilterError::InvalidPrefix(raw.to_owned()))?,
                    None => IPV6_MAX_PREFIX,
                };
                if prefix_len > IPV6_MAX_PREFIX {
                    return Err(IpFilterError::PrefixOutOfRange(prefix_len));
                }
                let bits: u128 = u128::from(v6);
                if prefix_len >= IPV4_MAPPED_PREFIX_BITS
                    && (bits & IPV6_HIGH_96_MASK) == IPV4_MAPPED_HIGH_96
                {
                    let v4_prefix: u8 = prefix_len - IPV4_MAPPED_PREFIX_BITS;
                    let mask: u32 = ipv4_prefix_mask(v4_prefix);
                    let network: u32 = (bits as u32) & mask;
                    return Ok(Self::V4 {
                        network,
                        mask,
                        prefix_len: v4_prefix,
                    });
                }
                let mask: u128 = ipv6_prefix_mask(prefix_len);
                let network: u128 = bits & mask;
                Ok(Self::V6 {
                    network,
                    mask,
                    prefix_len,
                })
            }
        }
    }

    /// Creates a host-exact CIDR entry (`/32` or `/128`) from an [`IpAddr`].
    ///
    /// # Arguments
    ///
    /// - `IpAddr` - Host IP address.
    ///
    /// # Returns
    ///
    /// - `Self` - Canonicalized single-host [`IpNet`].
    pub fn from_host(ip: IpAddr) -> Self {
        match canonicalize_ip(ip) {
            IpAddr::V4(v4) => Self::V4 {
                network: u32::from(v4),
                mask: u32::MAX,
                prefix_len: IPV4_MAX_PREFIX,
            },
            IpAddr::V6(v6) => Self::V6 {
                network: u128::from(v6),
                mask: u128::MAX,
                prefix_len: IPV6_MAX_PREFIX,
            },
        }
    }

    /// Reports whether `ip` belongs to this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `IpAddr` - Candidate IP address (IPv4-mapped IPv6 is canonicalized automatically).
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `ip` matches this network.
    #[inline]
    pub fn contains(&self, ip: IpAddr) -> bool {
        match (*self, canonicalize_ip(ip)) {
            (Self::V4 { network, mask, .. }, IpAddr::V4(v4)) => (u32::from(v4) & mask) == network,
            (Self::V6 { network, mask, .. }, IpAddr::V6(v6)) => (u128::from(v6) & mask) == network,
            _ => false,
        }
    }
}

/// Implements [`FromStr`] for [`IpNet`].
impl FromStr for IpNet {
    type Err = IpFilterError;

    /// Parses an [`IpNet`] via [`IpNet::parse`].
    ///
    /// # Arguments
    ///
    /// - `&str` - Input CIDR or IP string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, Self::Err>` - Parsed network or error.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// Context extraction helper for [`ClientIp`].
impl ClientIp {
    /// Retrieves the [`ClientIp`] injected by [`IpFilterHook`] from `ctx`.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Option<Self>` - Resolved client IP metadata when present.
    pub fn from_context(ctx: &Context) -> Option<Self> {
        ctx.try_get_attribute::<Self, _>(ATTR_CLIENT_IP)
    }
}

/// Default construction for [`CidrTable`].
impl Default for CidrTable {
    /// Constructs an empty [`CidrTable`].
    ///
    /// # Returns
    ///
    /// - `Self` - Empty CIDR lookup table.
    fn default() -> Self {
        Self::from_nets(&[])
    }
}

/// Inherent compilation and zero-allocation lookup methods for [`CidrTable`].
impl CidrTable {
    /// Compiles a slice of [`IpNet`] blocks into a `/8` radix-indexed lookup table.
    ///
    /// # Arguments
    ///
    /// - `&[IpNet]` - Source CIDR entries.
    ///
    /// # Returns
    ///
    /// - `Self` - Compiled lookup table ready for zero-allocation queries.
    pub fn from_nets(nets: &[IpNet]) -> Self {
        let mut v4_any: bool = false;
        let mut v6_any: bool = false;
        let mut v4_raw: Vec<(u32, u32)> = Vec::new();
        let mut v6_raw: Vec<(u128, u128)> = Vec::new();
        for net in nets {
            match *net {
                IpNet::V4 {
                    network,
                    mask,
                    prefix_len,
                } => {
                    if prefix_len == 0 {
                        v4_any = true;
                    } else if !v4_any {
                        v4_raw.push((network, network | !mask));
                    }
                }
                IpNet::V6 {
                    network,
                    mask,
                    prefix_len,
                } => {
                    if prefix_len == 0 {
                        v6_any = true;
                    } else if !v6_any {
                        v6_raw.push((network, network | !mask));
                    }
                }
            }
        }
        let v4: V4CidrIndex = if v4_any {
            V4CidrIndex::Any
        } else if v4_raw.is_empty() {
            V4CidrIndex::Empty
        } else {
            merge_v4_intervals(&mut v4_raw);
            if v4_raw.len() == 1 && v4_raw[0] == (0, u32::MAX) {
                V4CidrIndex::Any
            } else if v4_raw.len() <= CIDR_INLINE_LIMIT {
                let mut items: [(u32, u32); CIDR_INLINE_LIMIT] = [(0, 0); CIDR_INLINE_LIMIT];
                let count: usize = v4_raw.len();
                items[..count].copy_from_slice(&v4_raw);
                V4CidrIndex::Inline {
                    len: count as u8,
                    items,
                }
            } else {
                let mut full_slash8: [u64; 4] = [0u64; 4];
                let mut offsets: Box<[u32; CIDR_OFFSET_LEN]> = Box::new([0u32; CIDR_OFFSET_LEN]);
                let mut intervals: Vec<(u32, u32)> = Vec::with_capacity(v4_raw.len());
                for &(lo, hi) in &v4_raw {
                    let first_b: usize = (lo >> 24) as usize;
                    let last_b: usize = (hi >> 24) as usize;
                    for b in first_b..=last_b {
                        let b_lo: u32 = (b as u32) << 24;
                        let b_hi: u32 = b_lo | IPV4_SLASH8_HOST_MASK;
                        let c_lo: u32 = lo.max(b_lo);
                        let c_hi: u32 = hi.min(b_hi);
                        if c_lo == b_lo && c_hi == b_hi {
                            full_slash8[b >> 6] |= 1u64 << (b & 63);
                        } else {
                            offsets[b + 1] += 1;
                            intervals.push((c_lo, c_hi));
                        }
                    }
                }
                for i in 1..CIDR_OFFSET_LEN {
                    offsets[i] += offsets[i - 1];
                }
                V4CidrIndex::Radix(Box::new(V4CidrCsr {
                    full_slash8,
                    offsets,
                    intervals: intervals.into_boxed_slice(),
                }))
            }
        };
        let v6: V6CidrIndex = if v6_any {
            V6CidrIndex::Any
        } else if v6_raw.is_empty() {
            V6CidrIndex::Empty
        } else {
            merge_v6_intervals(&mut v6_raw);
            if v6_raw.len() == 1 && v6_raw[0] == (0, u128::MAX) {
                V6CidrIndex::Any
            } else if v6_raw.len() <= CIDR_INLINE_LIMIT {
                let mut items: [(u128, u128); CIDR_INLINE_LIMIT] = [(0, 0); CIDR_INLINE_LIMIT];
                let count: usize = v6_raw.len();
                items[..count].copy_from_slice(&v6_raw);
                V6CidrIndex::Inline {
                    len: count as u8,
                    items,
                }
            } else {
                let mut full_slash8: [u64; 4] = [0u64; 4];
                let mut offsets: Box<[u32; CIDR_OFFSET_LEN]> = Box::new([0u32; CIDR_OFFSET_LEN]);
                let mut intervals: Vec<(u128, u128)> = Vec::with_capacity(v6_raw.len());
                for &(lo, hi) in &v6_raw {
                    let first_b: usize = (lo >> 120) as usize;
                    let last_b: usize = (hi >> 120) as usize;
                    for b in first_b..=last_b {
                        let b_lo: u128 = (b as u128) << 120;
                        let b_hi: u128 = b_lo | IPV6_SLASH8_HOST_MASK;
                        let c_lo: u128 = lo.max(b_lo);
                        let c_hi: u128 = hi.min(b_hi);
                        if c_lo == b_lo && c_hi == b_hi {
                            full_slash8[b >> 6] |= 1u64 << (b & 63);
                        } else {
                            offsets[b + 1] += 1;
                            intervals.push((c_lo, c_hi));
                        }
                    }
                }
                for i in 1..CIDR_OFFSET_LEN {
                    offsets[i] += offsets[i - 1];
                }
                V6CidrIndex::Radix(Box::new(V6CidrCsr {
                    full_slash8,
                    offsets,
                    intervals: intervals.into_boxed_slice(),
                }))
            }
        };
        Self {
            v4,
            v6,
            entry_count: nets.len(),
        }
    }

    /// Reports whether this table contains zero CIDR entries.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        let Self { entry_count, .. } = self;
        *entry_count == 0
    }

    /// Returns the number of CIDR entries compiled into this table.
    ///
    /// # Returns
    ///
    /// - `usize` - Entry count.
    #[inline]
    pub fn len(&self) -> usize {
        let Self { entry_count, .. } = self;
        *entry_count
    }

    /// Tests whether `ip` matches any compiled CIDR entry without heap allocation.
    ///
    /// IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) are canonicalized to IPv4 prior to lookup.
    ///
    /// # Arguments
    ///
    /// - `IpAddr` - Candidate IP address.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `ip` matches at least one entry.
    #[inline]
    pub fn contains(&self, ip: IpAddr) -> bool {
        if self.is_empty() {
            return false;
        }
        match canonicalize_ip(ip) {
            IpAddr::V4(v4) => self.contains_v4(v4),
            IpAddr::V6(v6) => self.contains_v6(v6),
        }
    }

    /// Zero-allocation IPv4 lookup using `/8` radix indexing and binary search.
    ///
    /// # Arguments
    ///
    /// - `Ipv4Addr` - Candidate IPv4 address.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when matched.
    #[inline]
    pub fn contains_v4(&self, ip: Ipv4Addr) -> bool {
        let Self { v4, .. } = self;
        match v4 {
            V4CidrIndex::Empty => false,
            V4CidrIndex::Any => true,
            V4CidrIndex::Inline { len, items } => {
                let bits: u32 = u32::from(ip);
                let count: usize = *len as usize;
                let mut i: usize = 0;
                while i < count {
                    let (lo, hi): (u32, u32) = items[i];
                    if bits.wrapping_sub(lo) <= hi - lo {
                        return true;
                    }
                    i += 1;
                }
                false
            }
            V4CidrIndex::Radix(csr) => {
                let bits: u32 = u32::from(ip);
                let bucket: usize = (bits >> 24) as usize;
                if (csr.full_slash8[bucket >> 6] & (1u64 << (bucket & 63))) != 0 {
                    return true;
                }
                let start: usize = csr.offsets[bucket] as usize;
                let end: usize = csr.offsets[bucket + 1] as usize;
                if start == end {
                    return false;
                }
                intervals_contain_v4(&csr.intervals[start..end], bits)
            }
        }
    }

    /// Zero-allocation IPv6 lookup using `/8` radix indexing and binary search.
    ///
    /// # Arguments
    ///
    /// - `Ipv6Addr` - Candidate IPv6 address (must not be IPv4-mapped).
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when matched.
    #[inline]
    pub fn contains_v6(&self, ip: Ipv6Addr) -> bool {
        let Self { v6, .. } = self;
        match v6 {
            V6CidrIndex::Empty => false,
            V6CidrIndex::Any => true,
            V6CidrIndex::Inline { len, items } => {
                let bits: u128 = u128::from(ip);
                let count: usize = *len as usize;
                let mut i: usize = 0;
                while i < count {
                    let (lo, hi): (u128, u128) = items[i];
                    if bits.wrapping_sub(lo) <= hi - lo {
                        return true;
                    }
                    i += 1;
                }
                false
            }
            V6CidrIndex::Radix(csr) => {
                let bits: u128 = u128::from(ip);
                let bucket: usize = (bits >> 120) as usize;
                if (csr.full_slash8[bucket >> 6] & (1u64 << (bucket & 63))) != 0 {
                    return true;
                }
                let start: usize = csr.offsets[bucket] as usize;
                let end: usize = csr.offsets[bucket + 1] as usize;
                if start == end {
                    return false;
                }
                intervals_contain_v6(&csr.intervals[start..end], bits)
            }
        }
    }
}

/// Default construction for [`IpFilterConfig`].
impl Default for IpFilterConfig {
    /// Constructs a permissive default [`IpFilterConfig`] with no trusted proxies and `403 Forbidden` rejection.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            allowlist: Vec::new(),
            denylist: Vec::new(),
            trusted_proxies: Vec::new(),
            max_trusted_hops: DEFAULT_MAX_TRUSTED_HOPS,
            trust_forwarded_header: true,
            trust_x_real_ip: true,
            exempt_paths: Vec::new(),
            exempt_prefixes: Vec::new(),
            reject_status: HttpStatus::Forbidden,
            reject_content_type: DEFAULT_REJECT_CONTENT_TYPE.to_owned(),
            reject_body: DEFAULT_REJECT_BODY.to_vec(),
        }
    }
}

/// Fluent configuration builders for [`IpFilterConfig`].
impl IpFilterConfig {
    /// Parses and appends CIDR entries to the allowlist.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of CIDR or IP strings.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpFilterError>` - Updated configuration or parse error.
    pub fn with_allowlist<I, S>(mut self, cidrs: I) -> Result<Self, IpFilterError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        for spec in cidrs {
            let net: IpNet = IpNet::parse(spec.as_ref())?;
            self.get_mut_allowlist().push(net);
        }
        Ok(self)
    }

    /// Parses and appends CIDR entries to the denylist.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of CIDR or IP strings.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpFilterError>` - Updated configuration or parse error.
    pub fn with_denylist<I, S>(mut self, cidrs: I) -> Result<Self, IpFilterError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        for spec in cidrs {
            let net: IpNet = IpNet::parse(spec.as_ref())?;
            self.get_mut_denylist().push(net);
        }
        Ok(self)
    }

    /// Parses and appends trusted proxy CIDRs permitted to supply forwarding headers.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of CIDR or IP strings.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpFilterError>` - Updated configuration or parse error.
    pub fn with_trusted_proxies<I, S>(mut self, cidrs: I) -> Result<Self, IpFilterError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        for spec in cidrs {
            let net: IpNet = IpNet::parse(spec.as_ref())?;
            self.get_mut_trusted_proxies().push(net);
        }
        Ok(self)
    }

    /// Sets the maximum number of trusted proxy hops peeled right-to-left.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum hop count (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_max_trusted_hops(mut self, max_hops: usize) -> Self {
        self.set_max_trusted_hops(max_hops.max(1));
        self
    }

    /// Enables or disables RFC 7239 `Forwarded` header inspection.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether `Forwarded` is trusted behind trusted proxies.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_trust_forwarded_header(mut self, enabled: bool) -> Self {
        self.set_trust_forwarded_header(enabled);
        self
    }

    /// Enables or disables `X-Real-IP` fallback inspection.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether `X-Real-IP` is trusted behind trusted proxies.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_trust_x_real_ip(mut self, enabled: bool) -> Self {
        self.set_trust_x_real_ip(enabled);
        self
    }

    /// Sets exact request paths exempted from IP blocking.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of exact request paths (for example `"/healthz"`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
        self
    }

    /// Sets path prefixes exempted from IP blocking on segment boundaries.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of path prefixes (for example `"/public"`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
        self
    }

    /// Customizes the HTTP status code, `Content-Type`, and body sent for rejected requests.
    ///
    /// # Arguments
    ///
    /// - `HttpStatus` - Rejection status code (for example `HttpStatus::Forbidden`).
    /// - `C` - `Content-Type` header value.
    /// - `B` - Rejection payload bytes.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_reject_response<C, B>(
        mut self,
        status: HttpStatus,
        content_type: C,
        body: B,
    ) -> Self
    where
        C: Into<String>,
        B: Into<Vec<u8>>,
    {
        self.set_reject_status(status)
            .set_reject_content_type(content_type.into())
            .set_reject_body(body.into());
        self
    }
}

/// Inherent compilation, IP resolution, and filtering engine for [`CompiledIpFilter`].
impl CompiledIpFilter {
    /// Precompiles `config` into radix CIDR tables and a pre-serialized rejection wire buffer.
    ///
    /// # Arguments
    ///
    /// - `IpFilterConfig` - Source filter policy.
    ///
    /// # Returns
    ///
    /// - `Self` - Compiled zero-allocation IP filter.
    pub fn compile(config: IpFilterConfig) -> Self {
        let allowlist: CidrTable = CidrTable::from_nets(config.get_allowlist());
        let denylist: CidrTable = CidrTable::from_nets(config.get_denylist());
        let trusted_proxies: CidrTable = CidrTable::from_nets(config.get_trusted_proxies());
        let mut unique_exempt: Vec<String> = config
            .get_exempt_paths()
            .iter()
            .filter(|p: &&String| !p.is_empty())
            .cloned()
            .collect();
        unique_exempt.sort_unstable();
        unique_exempt.dedup();
        let (exempt_small, exempt_set): (Box<[String]>, Option<HashSetXxHash3_64<String>>) =
            if unique_exempt.len() <= EXEMPT_SET_THRESHOLD {
                (unique_exempt.into_boxed_slice(), None)
            } else {
                let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
                for path in unique_exempt {
                    set.insert(path);
                }
                (Box::new([]), Some(set))
            };
        let exempt_prefixes: Box<[String]> = config
            .get_exempt_prefixes()
            .iter()
            .filter(|p: &&String| !p.trim().is_empty())
            .map(|p: &String| normalize_prefix(p))
            .collect::<Vec<String>>()
            .into_boxed_slice();
        let mut reject_resp: Response = Response::default();
        reject_resp
            .set_status_code(config.get_reject_status().code())
            .set_header(CONTENT_TYPE, config.get_reject_content_type())
            .set_body(config.get_reject_body().clone());
        let prebuilt_reject_wire: Vec<u8> = reject_resp.build();
        Self {
            config,
            allowlist,
            denylist,
            trusted_proxies,
            exempt_small,
            exempt_set,
            exempt_prefixes,
            prebuilt_reject_wire,
        }
    }

    /// Returns the source [`IpFilterConfig`].
    ///
    /// # Returns
    ///
    /// - `&IpFilterConfig` - Source configuration.
    pub fn get_config(&self) -> &IpFilterConfig {
        let Self { config, .. } = self;
        config
    }

    /// Returns the pre-serialized HTTP rejection response wire bytes.
    ///
    /// # Returns
    ///
    /// - `&Vec<u8>` - Prebuilt wire response buffer.
    #[inline]
    pub fn get_prebuilt_reject_wire(&self) -> &Vec<u8> {
        let Self {
            prebuilt_reject_wire,
            ..
        } = self;
        prebuilt_reject_wire
    }

    /// Reports whether `path` is exempted from allowlist/denylist enforcement.
    ///
    /// # Arguments
    ///
    /// - `&str` - Incoming request path.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when exempt.
    #[inline]
    pub fn is_path_exempt(&self, path: &str) -> bool {
        let Self {
            exempt_small,
            exempt_set,
            exempt_prefixes,
            ..
        } = self;
        for exact in exempt_small.iter() {
            if exact.as_str() == path {
                return true;
            }
        }
        if let Some(set) = exempt_set
            && set.contains(path)
        {
            return true;
        }
        exempt_prefixes
            .iter()
            .any(|prefix: &String| path_matches_prefix(path, prefix))
    }

    /// Resolves the real client IP from `peer_ip` and trusted forwarding headers with zero heap allocations.
    ///
    /// Forwarding headers are strictly ignored unless `peer_ip` matches `trusted_proxies`.
    ///
    /// # Arguments
    ///
    /// - `Option<IpAddr>` - Direct transport peer IP address.
    /// - `&RequestHeaders` - Incoming request headers.
    ///
    /// # Returns
    ///
    /// - `Option<ClientIp>` - Resolved client IP metadata.
    #[inline]
    pub fn resolve_client_ip(
        &self,
        peer_ip: Option<IpAddr>,
        headers: &RequestHeaders,
    ) -> Option<ClientIp> {
        let Self {
            config,
            trusted_proxies,
            ..
        } = self;
        let canonical_peer: IpAddr = canonicalize_ip(peer_ip?);
        if trusted_proxies.is_empty() || !trusted_proxies.contains(canonical_peer) {
            return Some(ClientIp {
                ip: canonical_peer,
                peer_ip: Some(canonical_peer),
                via_proxy: false,
            });
        }
        let max_hops: usize = config.get_max_trusted_hops();
        if let Some(xff_vals) = find_header_values(headers, X_FORWARDED_FOR)
            && let Some(resolved) = peel_xff_right_to_left(xff_vals, trusted_proxies, max_hops)
        {
            return Some(ClientIp {
                ip: resolved,
                peer_ip: Some(canonical_peer),
                via_proxy: true,
            });
        }
        if config.get_trust_forwarded_header()
            && let Some(fwd_vals) = find_header_values(headers, FORWARDED)
            && let Some(resolved) =
                peel_forwarded_right_to_left(fwd_vals, trusted_proxies, max_hops)
        {
            return Some(ClientIp {
                ip: resolved,
                peer_ip: Some(canonical_peer),
                via_proxy: true,
            });
        }
        if config.get_trust_x_real_ip()
            && let Some(real_vals) = find_header_values(headers, X_REAL_IP)
            && let Some(raw_val) = real_vals.back()
            && let Some(resolved) = parse_forwarded_ip_token(raw_val)
        {
            return Some(ClientIp {
                ip: resolved,
                peer_ip: Some(canonical_peer),
                via_proxy: true,
            });
        }
        Some(ClientIp {
            ip: canonical_peer,
            peer_ip: Some(canonical_peer),
            via_proxy: false,
        })
    }

    /// Evaluates whether `ip` is permitted by the compiled denylist and allowlist.
    ///
    /// Denylist rules always take precedence over allowlist rules.
    ///
    /// # Arguments
    ///
    /// - `IpAddr` - Resolved client IP.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when permitted; `false` when rejected.
    #[inline]
    pub fn is_ip_allowed(&self, ip: IpAddr) -> bool {
        let Self {
            allowlist,
            denylist,
            ..
        } = self;
        let canonical: IpAddr = canonicalize_ip(ip);
        match canonical {
            IpAddr::V4(v4) => {
                if !denylist.is_empty() && denylist.contains_v4(v4) {
                    return false;
                }
                if !allowlist.is_empty() && !allowlist.contains_v4(v4) {
                    return false;
                }
            }
            IpAddr::V6(v6) => {
                if !denylist.is_empty() && denylist.contains_v6(v6) {
                    return false;
                }
                if !allowlist.is_empty() && !allowlist.contains_v6(v6) {
                    return false;
                }
            }
        }
        true
    }

    /// Resolves `ClientIp`, stores it in `ctx` under [`ATTR_CLIENT_IP`], and enforces allow/deny rules.
    ///
    /// # Arguments
    ///
    /// - `Option<IpAddr>` - Direct transport peer IP address.
    /// - `&mut Context` - Incoming request and outgoing response context.
    ///
    /// # Returns
    ///
    /// - `IpFilterDecision` - Enforcement outcome and resolved client IP metadata.
    pub fn evaluate(&self, peer_ip: Option<IpAddr>, ctx: &mut Context) -> IpFilterDecision {
        let Self {
            allowlist, config, ..
        } = self;
        let client_ip: Option<ClientIp> =
            self.resolve_client_ip(peer_ip, ctx.get_request().get_headers());
        if let Some(resolved) = client_ip {
            ctx.set_attribute(ATTR_CLIENT_IP, resolved);
        }
        if self.is_path_exempt(ctx.get_request().get_path()) {
            return IpFilterDecision {
                action: IpFilterAction::Exempt,
                client_ip,
            };
        }
        let allowed: bool = match client_ip {
            Some(resolved) => self.is_ip_allowed(resolved.get_ip()),
            None => allowlist.is_empty(),
        };
        if allowed {
            return IpFilterDecision {
                action: IpFilterAction::Allow,
                client_ip,
            };
        }
        ctx.get_mut_response()
            .set_status_code(config.get_reject_status().code())
            .set_header(CONTENT_TYPE, config.get_reject_content_type())
            .set_body(config.get_reject_body().clone());
        IpFilterDecision {
            action: IpFilterAction::Deny,
            client_ip,
        }
    }
}

/// Process-wide singleton management for [`IpFilterPlugin`].
impl IpFilterPlugin {
    /// Initializes the global [`IpFilterPlugin`] once with `config`.
    ///
    /// # Arguments
    ///
    /// - `IpFilterConfig` - IP extraction and CIDR filtering configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init(config: IpFilterConfig) -> &'static Self {
        IP_FILTER_PLUGIN.get_or_init(|| Self {
            compiled: CompiledIpFilter::compile(config),
        })
    }

    /// Returns the initialized global [`IpFilterPlugin`], if [`IpFilterPlugin::init`] was called.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline]
    pub fn get() -> Option<&'static Self> {
        IP_FILTER_PLUGIN.get()
    }

    /// Returns the compiled [`CompiledIpFilter`] engine.
    ///
    /// # Returns
    ///
    /// - `&CompiledIpFilter` - Compiled filter engine.
    #[inline]
    pub fn get_compiled(&self) -> &CompiledIpFilter {
        let Self { compiled } = self;
        compiled
    }
}

/// Implements [`ServerHook`] for [`IpFilterHook`].
impl ServerHook for IpFilterHook {
    /// Constructs a per-request [`IpFilterHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Extracts client IP into `Context` and short-circuits disallowed peers with prebuilt wire bytes.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` after sending prebuilt rejection bytes; `Status::Continue` otherwise.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = IpFilterPlugin::get() else {
            return Status::Continue;
        };
        let compiled: &CompiledIpFilter = plugin.get_compiled();
        let peer_ip: Option<IpAddr> = stream
            .get_peer_addr()
            .ok()
            .map(|addr: SocketAddr| addr.ip());
        let client_ip: Option<ClientIp> =
            compiled.resolve_client_ip(peer_ip, ctx.get_request().get_headers());
        if let Some(resolved) = client_ip {
            ctx.set_attribute(ATTR_CLIENT_IP, resolved);
        }
        if compiled.is_path_exempt(ctx.get_request().get_path()) {
            return Status::Continue;
        }
        let allowed: bool = match client_ip {
            Some(resolved) => compiled.is_ip_allowed(resolved.get_ip()),
            None => compiled.allowlist.is_empty(),
        };
        if allowed {
            return Status::Continue;
        }
        let _: Result<(), ResponseError> =
            stream.try_send(compiled.get_prebuilt_reject_wire()).await;
        Status::Reject
    }
}