Skip to main content

hyperlane_plugin_ip_filter/
impl.rs

1use super::*;
2
3/// Formats [`IpFilterError`] for display diagnostics.
4impl Display for IpFilterError {
5    /// Renders a human-readable CIDR parsing error message.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Output formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting outcome.
14    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15        match self {
16            Self::EmptyCidr => f.write_str(ERR_EMPTY_CIDR),
17            Self::InvalidIp(raw) => write!(f, "{ERR_INVALID_IP}: {raw}"),
18            Self::InvalidPrefix(raw) => write!(f, "{ERR_INVALID_PREFIX}: {raw}"),
19            Self::PrefixOutOfRange(len) => write!(f, "{ERR_PREFIX_OUT_OF_RANGE}: /{len}"),
20        }
21    }
22}
23
24/// Marks [`IpFilterError`] as a standard error type.
25impl Error for IpFilterError {}
26
27/// Inherent constructors and membership checks for [`IpNet`].
28impl IpNet {
29    /// 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"`).
30    ///
31    /// IPv4-mapped IPv6 addresses and subnets (`>= /96` inside `::ffff:0:0/96`) are canonicalized to IPv4.
32    ///
33    /// # Arguments
34    ///
35    /// - `&str` - IP or CIDR string.
36    ///
37    /// # Returns
38    ///
39    /// - `Result<Self, IpFilterError>` - Canonicalized CIDR block or parse error.
40    pub fn parse(spec: &str) -> Result<Self, IpFilterError> {
41        let trimmed: &str = spec.trim();
42        if trimmed.is_empty() {
43            return Err(IpFilterError::EmptyCidr);
44        }
45        let (addr_part, prefix_part): (&str, Option<&str>) = match trimmed.split_once('/') {
46            Some((addr, prefix)) => (addr.trim(), Some(prefix.trim())),
47            None => (trimmed, None),
48        };
49        let ip: IpAddr = IpAddr::from_str(addr_part)
50            .map_err(|_| IpFilterError::InvalidIp(addr_part.to_owned()))?;
51        match ip {
52            IpAddr::V4(v4) => {
53                let prefix_len: u8 = match prefix_part {
54                    Some(raw) => raw
55                        .parse::<u8>()
56                        .map_err(|_| IpFilterError::InvalidPrefix(raw.to_owned()))?,
57                    None => IPV4_MAX_PREFIX,
58                };
59                if prefix_len > IPV4_MAX_PREFIX {
60                    return Err(IpFilterError::PrefixOutOfRange(prefix_len));
61                }
62                let mask: u32 = ipv4_prefix_mask(prefix_len);
63                let network: u32 = u32::from(v4) & mask;
64                Ok(Self::V4 {
65                    network,
66                    mask,
67                    prefix_len,
68                })
69            }
70            IpAddr::V6(v6) => {
71                let prefix_len: u8 = match prefix_part {
72                    Some(raw) => raw
73                        .parse::<u8>()
74                        .map_err(|_| IpFilterError::InvalidPrefix(raw.to_owned()))?,
75                    None => IPV6_MAX_PREFIX,
76                };
77                if prefix_len > IPV6_MAX_PREFIX {
78                    return Err(IpFilterError::PrefixOutOfRange(prefix_len));
79                }
80                let bits: u128 = u128::from(v6);
81                if prefix_len >= IPV4_MAPPED_PREFIX_BITS
82                    && (bits & IPV6_HIGH_96_MASK) == IPV4_MAPPED_HIGH_96
83                {
84                    let v4_prefix: u8 = prefix_len - IPV4_MAPPED_PREFIX_BITS;
85                    let mask: u32 = ipv4_prefix_mask(v4_prefix);
86                    let network: u32 = (bits as u32) & mask;
87                    return Ok(Self::V4 {
88                        network,
89                        mask,
90                        prefix_len: v4_prefix,
91                    });
92                }
93                let mask: u128 = ipv6_prefix_mask(prefix_len);
94                let network: u128 = bits & mask;
95                Ok(Self::V6 {
96                    network,
97                    mask,
98                    prefix_len,
99                })
100            }
101        }
102    }
103
104    /// Creates a host-exact CIDR entry (`/32` or `/128`) from an [`IpAddr`].
105    ///
106    /// # Arguments
107    ///
108    /// - `IpAddr` - Host IP address.
109    ///
110    /// # Returns
111    ///
112    /// - `Self` - Canonicalized single-host [`IpNet`].
113    pub fn from_host(ip: IpAddr) -> Self {
114        match canonicalize_ip(ip) {
115            IpAddr::V4(v4) => Self::V4 {
116                network: u32::from(v4),
117                mask: u32::MAX,
118                prefix_len: IPV4_MAX_PREFIX,
119            },
120            IpAddr::V6(v6) => Self::V6 {
121                network: u128::from(v6),
122                mask: u128::MAX,
123                prefix_len: IPV6_MAX_PREFIX,
124            },
125        }
126    }
127
128    /// Reports whether `ip` belongs to this CIDR block.
129    ///
130    /// # Arguments
131    ///
132    /// - `IpAddr` - Candidate IP address (IPv4-mapped IPv6 is canonicalized automatically).
133    ///
134    /// # Returns
135    ///
136    /// - `bool` - `true` when `ip` matches this network.
137    #[inline]
138    pub fn contains(&self, ip: IpAddr) -> bool {
139        match (*self, canonicalize_ip(ip)) {
140            (Self::V4 { network, mask, .. }, IpAddr::V4(v4)) => (u32::from(v4) & mask) == network,
141            (Self::V6 { network, mask, .. }, IpAddr::V6(v6)) => (u128::from(v6) & mask) == network,
142            _ => false,
143        }
144    }
145}
146
147/// Implements [`FromStr`] for [`IpNet`].
148impl FromStr for IpNet {
149    type Err = IpFilterError;
150
151    /// Parses an [`IpNet`] via [`IpNet::parse`].
152    ///
153    /// # Arguments
154    ///
155    /// - `&str` - Input CIDR or IP string.
156    ///
157    /// # Returns
158    ///
159    /// - `Result<Self, Self::Err>` - Parsed network or error.
160    fn from_str(s: &str) -> Result<Self, Self::Err> {
161        Self::parse(s)
162    }
163}
164
165/// Context extraction helper for [`ClientIp`].
166impl ClientIp {
167    /// Retrieves the [`ClientIp`] injected by [`IpFilterHook`] from `ctx`.
168    ///
169    /// # Arguments
170    ///
171    /// - `&Context` - Active Hyperlane request context.
172    ///
173    /// # Returns
174    ///
175    /// - `Option<Self>` - Resolved client IP metadata when present.
176    pub fn from_context(ctx: &Context) -> Option<Self> {
177        ctx.try_get_attribute::<Self, _>(ATTR_CLIENT_IP)
178    }
179}
180
181/// Default construction for [`CidrTable`].
182impl Default for CidrTable {
183    /// Constructs an empty [`CidrTable`].
184    ///
185    /// # Returns
186    ///
187    /// - `Self` - Empty CIDR lookup table.
188    fn default() -> Self {
189        Self::from_nets(&[])
190    }
191}
192
193/// Inherent compilation and zero-allocation lookup methods for [`CidrTable`].
194impl CidrTable {
195    /// Compiles a slice of [`IpNet`] blocks into a `/8` radix-indexed lookup table.
196    ///
197    /// # Arguments
198    ///
199    /// - `&[IpNet]` - Source CIDR entries.
200    ///
201    /// # Returns
202    ///
203    /// - `Self` - Compiled lookup table ready for zero-allocation queries.
204    pub fn from_nets(nets: &[IpNet]) -> Self {
205        let mut v4_any: bool = false;
206        let mut v6_any: bool = false;
207        let mut v4_raw: Vec<(u32, u32)> = Vec::new();
208        let mut v6_raw: Vec<(u128, u128)> = Vec::new();
209        for net in nets {
210            match *net {
211                IpNet::V4 {
212                    network,
213                    mask,
214                    prefix_len,
215                } => {
216                    if prefix_len == 0 {
217                        v4_any = true;
218                    } else if !v4_any {
219                        v4_raw.push((network, network | !mask));
220                    }
221                }
222                IpNet::V6 {
223                    network,
224                    mask,
225                    prefix_len,
226                } => {
227                    if prefix_len == 0 {
228                        v6_any = true;
229                    } else if !v6_any {
230                        v6_raw.push((network, network | !mask));
231                    }
232                }
233            }
234        }
235        let v4: V4CidrIndex = if v4_any {
236            V4CidrIndex::Any
237        } else if v4_raw.is_empty() {
238            V4CidrIndex::Empty
239        } else {
240            merge_v4_intervals(&mut v4_raw);
241            if v4_raw.len() == 1 && v4_raw[0] == (0, u32::MAX) {
242                V4CidrIndex::Any
243            } else if v4_raw.len() <= CIDR_INLINE_LIMIT {
244                let mut items: [(u32, u32); CIDR_INLINE_LIMIT] = [(0, 0); CIDR_INLINE_LIMIT];
245                let count: usize = v4_raw.len();
246                items[..count].copy_from_slice(&v4_raw);
247                V4CidrIndex::Inline {
248                    len: count as u8,
249                    items,
250                }
251            } else {
252                let mut full_slash8: [u64; 4] = [0u64; 4];
253                let mut offsets: Box<[u32; CIDR_OFFSET_LEN]> = Box::new([0u32; CIDR_OFFSET_LEN]);
254                let mut intervals: Vec<(u32, u32)> = Vec::with_capacity(v4_raw.len());
255                for &(lo, hi) in &v4_raw {
256                    let first_b: usize = (lo >> 24) as usize;
257                    let last_b: usize = (hi >> 24) as usize;
258                    for b in first_b..=last_b {
259                        let b_lo: u32 = (b as u32) << 24;
260                        let b_hi: u32 = b_lo | IPV4_SLASH8_HOST_MASK;
261                        let c_lo: u32 = lo.max(b_lo);
262                        let c_hi: u32 = hi.min(b_hi);
263                        if c_lo == b_lo && c_hi == b_hi {
264                            full_slash8[b >> 6] |= 1u64 << (b & 63);
265                        } else {
266                            offsets[b + 1] += 1;
267                            intervals.push((c_lo, c_hi));
268                        }
269                    }
270                }
271                for i in 1..CIDR_OFFSET_LEN {
272                    offsets[i] += offsets[i - 1];
273                }
274                V4CidrIndex::Radix(Box::new(V4CidrCsr {
275                    full_slash8,
276                    offsets,
277                    intervals: intervals.into_boxed_slice(),
278                }))
279            }
280        };
281        let v6: V6CidrIndex = if v6_any {
282            V6CidrIndex::Any
283        } else if v6_raw.is_empty() {
284            V6CidrIndex::Empty
285        } else {
286            merge_v6_intervals(&mut v6_raw);
287            if v6_raw.len() == 1 && v6_raw[0] == (0, u128::MAX) {
288                V6CidrIndex::Any
289            } else if v6_raw.len() <= CIDR_INLINE_LIMIT {
290                let mut items: [(u128, u128); CIDR_INLINE_LIMIT] = [(0, 0); CIDR_INLINE_LIMIT];
291                let count: usize = v6_raw.len();
292                items[..count].copy_from_slice(&v6_raw);
293                V6CidrIndex::Inline {
294                    len: count as u8,
295                    items,
296                }
297            } else {
298                let mut full_slash8: [u64; 4] = [0u64; 4];
299                let mut offsets: Box<[u32; CIDR_OFFSET_LEN]> = Box::new([0u32; CIDR_OFFSET_LEN]);
300                let mut intervals: Vec<(u128, u128)> = Vec::with_capacity(v6_raw.len());
301                for &(lo, hi) in &v6_raw {
302                    let first_b: usize = (lo >> 120) as usize;
303                    let last_b: usize = (hi >> 120) as usize;
304                    for b in first_b..=last_b {
305                        let b_lo: u128 = (b as u128) << 120;
306                        let b_hi: u128 = b_lo | IPV6_SLASH8_HOST_MASK;
307                        let c_lo: u128 = lo.max(b_lo);
308                        let c_hi: u128 = hi.min(b_hi);
309                        if c_lo == b_lo && c_hi == b_hi {
310                            full_slash8[b >> 6] |= 1u64 << (b & 63);
311                        } else {
312                            offsets[b + 1] += 1;
313                            intervals.push((c_lo, c_hi));
314                        }
315                    }
316                }
317                for i in 1..CIDR_OFFSET_LEN {
318                    offsets[i] += offsets[i - 1];
319                }
320                V6CidrIndex::Radix(Box::new(V6CidrCsr {
321                    full_slash8,
322                    offsets,
323                    intervals: intervals.into_boxed_slice(),
324                }))
325            }
326        };
327        Self {
328            v4,
329            v6,
330            entry_count: nets.len(),
331        }
332    }
333
334    /// Reports whether this table contains zero CIDR entries.
335    ///
336    /// # Returns
337    ///
338    /// - `bool` - `true` when empty.
339    #[inline]
340    pub fn is_empty(&self) -> bool {
341        let Self { entry_count, .. } = self;
342        *entry_count == 0
343    }
344
345    /// Returns the number of CIDR entries compiled into this table.
346    ///
347    /// # Returns
348    ///
349    /// - `usize` - Entry count.
350    #[inline]
351    pub fn len(&self) -> usize {
352        let Self { entry_count, .. } = self;
353        *entry_count
354    }
355
356    /// Tests whether `ip` matches any compiled CIDR entry without heap allocation.
357    ///
358    /// IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) are canonicalized to IPv4 prior to lookup.
359    ///
360    /// # Arguments
361    ///
362    /// - `IpAddr` - Candidate IP address.
363    ///
364    /// # Returns
365    ///
366    /// - `bool` - `true` when `ip` matches at least one entry.
367    #[inline]
368    pub fn contains(&self, ip: IpAddr) -> bool {
369        if self.is_empty() {
370            return false;
371        }
372        match canonicalize_ip(ip) {
373            IpAddr::V4(v4) => self.contains_v4(v4),
374            IpAddr::V6(v6) => self.contains_v6(v6),
375        }
376    }
377
378    /// Zero-allocation IPv4 lookup using `/8` radix indexing and binary search.
379    ///
380    /// # Arguments
381    ///
382    /// - `Ipv4Addr` - Candidate IPv4 address.
383    ///
384    /// # Returns
385    ///
386    /// - `bool` - `true` when matched.
387    #[inline]
388    pub fn contains_v4(&self, ip: Ipv4Addr) -> bool {
389        let Self { v4, .. } = self;
390        match v4 {
391            V4CidrIndex::Empty => false,
392            V4CidrIndex::Any => true,
393            V4CidrIndex::Inline { len, items } => {
394                let bits: u32 = u32::from(ip);
395                let count: usize = *len as usize;
396                let mut i: usize = 0;
397                while i < count {
398                    let (lo, hi): (u32, u32) = items[i];
399                    if bits.wrapping_sub(lo) <= hi - lo {
400                        return true;
401                    }
402                    i += 1;
403                }
404                false
405            }
406            V4CidrIndex::Radix(csr) => {
407                let bits: u32 = u32::from(ip);
408                let bucket: usize = (bits >> 24) as usize;
409                if (csr.full_slash8[bucket >> 6] & (1u64 << (bucket & 63))) != 0 {
410                    return true;
411                }
412                let start: usize = csr.offsets[bucket] as usize;
413                let end: usize = csr.offsets[bucket + 1] as usize;
414                if start == end {
415                    return false;
416                }
417                intervals_contain_v4(&csr.intervals[start..end], bits)
418            }
419        }
420    }
421
422    /// Zero-allocation IPv6 lookup using `/8` radix indexing and binary search.
423    ///
424    /// # Arguments
425    ///
426    /// - `Ipv6Addr` - Candidate IPv6 address (must not be IPv4-mapped).
427    ///
428    /// # Returns
429    ///
430    /// - `bool` - `true` when matched.
431    #[inline]
432    pub fn contains_v6(&self, ip: Ipv6Addr) -> bool {
433        let Self { v6, .. } = self;
434        match v6 {
435            V6CidrIndex::Empty => false,
436            V6CidrIndex::Any => true,
437            V6CidrIndex::Inline { len, items } => {
438                let bits: u128 = u128::from(ip);
439                let count: usize = *len as usize;
440                let mut i: usize = 0;
441                while i < count {
442                    let (lo, hi): (u128, u128) = items[i];
443                    if bits.wrapping_sub(lo) <= hi - lo {
444                        return true;
445                    }
446                    i += 1;
447                }
448                false
449            }
450            V6CidrIndex::Radix(csr) => {
451                let bits: u128 = u128::from(ip);
452                let bucket: usize = (bits >> 120) as usize;
453                if (csr.full_slash8[bucket >> 6] & (1u64 << (bucket & 63))) != 0 {
454                    return true;
455                }
456                let start: usize = csr.offsets[bucket] as usize;
457                let end: usize = csr.offsets[bucket + 1] as usize;
458                if start == end {
459                    return false;
460                }
461                intervals_contain_v6(&csr.intervals[start..end], bits)
462            }
463        }
464    }
465}
466
467/// Default construction for [`IpFilterConfig`].
468impl Default for IpFilterConfig {
469    /// Constructs a permissive default [`IpFilterConfig`] with no trusted proxies and `403 Forbidden` rejection.
470    ///
471    /// # Returns
472    ///
473    /// - `Self` - Default configuration.
474    fn default() -> Self {
475        Self {
476            allowlist: Vec::new(),
477            denylist: Vec::new(),
478            trusted_proxies: Vec::new(),
479            max_trusted_hops: DEFAULT_MAX_TRUSTED_HOPS,
480            trust_forwarded_header: true,
481            trust_x_real_ip: true,
482            exempt_paths: Vec::new(),
483            exempt_prefixes: Vec::new(),
484            reject_status: HttpStatus::Forbidden,
485            reject_content_type: DEFAULT_REJECT_CONTENT_TYPE.to_owned(),
486            reject_body: DEFAULT_REJECT_BODY.to_vec(),
487        }
488    }
489}
490
491/// Fluent configuration builders for [`IpFilterConfig`].
492impl IpFilterConfig {
493    /// Parses and appends CIDR entries to the allowlist.
494    ///
495    /// # Arguments
496    ///
497    /// - `I` - Iterator of CIDR or IP strings.
498    ///
499    /// # Returns
500    ///
501    /// - `Result<Self, IpFilterError>` - Updated configuration or parse error.
502    pub fn with_allowlist<I, S>(mut self, cidrs: I) -> Result<Self, IpFilterError>
503    where
504        I: IntoIterator<Item = S>,
505        S: AsRef<str>,
506    {
507        for spec in cidrs {
508            let net: IpNet = IpNet::parse(spec.as_ref())?;
509            self.get_mut_allowlist().push(net);
510        }
511        Ok(self)
512    }
513
514    /// Parses and appends CIDR entries to the denylist.
515    ///
516    /// # Arguments
517    ///
518    /// - `I` - Iterator of CIDR or IP strings.
519    ///
520    /// # Returns
521    ///
522    /// - `Result<Self, IpFilterError>` - Updated configuration or parse error.
523    pub fn with_denylist<I, S>(mut self, cidrs: I) -> Result<Self, IpFilterError>
524    where
525        I: IntoIterator<Item = S>,
526        S: AsRef<str>,
527    {
528        for spec in cidrs {
529            let net: IpNet = IpNet::parse(spec.as_ref())?;
530            self.get_mut_denylist().push(net);
531        }
532        Ok(self)
533    }
534
535    /// Parses and appends trusted proxy CIDRs permitted to supply forwarding headers.
536    ///
537    /// # Arguments
538    ///
539    /// - `I` - Iterator of CIDR or IP strings.
540    ///
541    /// # Returns
542    ///
543    /// - `Result<Self, IpFilterError>` - Updated configuration or parse error.
544    pub fn with_trusted_proxies<I, S>(mut self, cidrs: I) -> Result<Self, IpFilterError>
545    where
546        I: IntoIterator<Item = S>,
547        S: AsRef<str>,
548    {
549        for spec in cidrs {
550            let net: IpNet = IpNet::parse(spec.as_ref())?;
551            self.get_mut_trusted_proxies().push(net);
552        }
553        Ok(self)
554    }
555
556    /// Sets the maximum number of trusted proxy hops peeled right-to-left.
557    ///
558    /// # Arguments
559    ///
560    /// - `usize` - Maximum hop count (`>= 1`).
561    ///
562    /// # Returns
563    ///
564    /// - `Self` - Updated configuration.
565    pub fn with_max_trusted_hops(mut self, max_hops: usize) -> Self {
566        self.set_max_trusted_hops(max_hops.max(1));
567        self
568    }
569
570    /// Enables or disables RFC 7239 `Forwarded` header inspection.
571    ///
572    /// # Arguments
573    ///
574    /// - `bool` - Whether `Forwarded` is trusted behind trusted proxies.
575    ///
576    /// # Returns
577    ///
578    /// - `Self` - Updated configuration.
579    pub fn with_trust_forwarded_header(mut self, enabled: bool) -> Self {
580        self.set_trust_forwarded_header(enabled);
581        self
582    }
583
584    /// Enables or disables `X-Real-IP` fallback inspection.
585    ///
586    /// # Arguments
587    ///
588    /// - `bool` - Whether `X-Real-IP` is trusted behind trusted proxies.
589    ///
590    /// # Returns
591    ///
592    /// - `Self` - Updated configuration.
593    pub fn with_trust_x_real_ip(mut self, enabled: bool) -> Self {
594        self.set_trust_x_real_ip(enabled);
595        self
596    }
597
598    /// Sets exact request paths exempted from IP blocking.
599    ///
600    /// # Arguments
601    ///
602    /// - `I` - Iterator of exact request paths (for example `"/healthz"`).
603    ///
604    /// # Returns
605    ///
606    /// - `Self` - Updated configuration.
607    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
608    where
609        I: IntoIterator<Item = S>,
610        S: Into<String>,
611    {
612        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
613        self
614    }
615
616    /// Sets path prefixes exempted from IP blocking on segment boundaries.
617    ///
618    /// # Arguments
619    ///
620    /// - `I` - Iterator of path prefixes (for example `"/public"`).
621    ///
622    /// # Returns
623    ///
624    /// - `Self` - Updated configuration.
625    pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
626    where
627        I: IntoIterator<Item = S>,
628        S: Into<String>,
629    {
630        self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
631        self
632    }
633
634    /// Customizes the HTTP status code, `Content-Type`, and body sent for rejected requests.
635    ///
636    /// # Arguments
637    ///
638    /// - `HttpStatus` - Rejection status code (for example `HttpStatus::Forbidden`).
639    /// - `C` - `Content-Type` header value.
640    /// - `B` - Rejection payload bytes.
641    ///
642    /// # Returns
643    ///
644    /// - `Self` - Updated configuration.
645    pub fn with_reject_response<C, B>(
646        mut self,
647        status: HttpStatus,
648        content_type: C,
649        body: B,
650    ) -> Self
651    where
652        C: Into<String>,
653        B: Into<Vec<u8>>,
654    {
655        self.set_reject_status(status)
656            .set_reject_content_type(content_type.into())
657            .set_reject_body(body.into());
658        self
659    }
660}
661
662/// Inherent compilation, IP resolution, and filtering engine for [`CompiledIpFilter`].
663impl CompiledIpFilter {
664    /// Precompiles `config` into radix CIDR tables and a pre-serialized rejection wire buffer.
665    ///
666    /// # Arguments
667    ///
668    /// - `IpFilterConfig` - Source filter policy.
669    ///
670    /// # Returns
671    ///
672    /// - `Self` - Compiled zero-allocation IP filter.
673    pub fn compile(config: IpFilterConfig) -> Self {
674        let allowlist: CidrTable = CidrTable::from_nets(config.get_allowlist());
675        let denylist: CidrTable = CidrTable::from_nets(config.get_denylist());
676        let trusted_proxies: CidrTable = CidrTable::from_nets(config.get_trusted_proxies());
677        let mut unique_exempt: Vec<String> = config
678            .get_exempt_paths()
679            .iter()
680            .filter(|p: &&String| !p.is_empty())
681            .cloned()
682            .collect();
683        unique_exempt.sort_unstable();
684        unique_exempt.dedup();
685        let (exempt_small, exempt_set): (Box<[String]>, Option<HashSetXxHash3_64<String>>) =
686            if unique_exempt.len() <= EXEMPT_SET_THRESHOLD {
687                (unique_exempt.into_boxed_slice(), None)
688            } else {
689                let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
690                for path in unique_exempt {
691                    set.insert(path);
692                }
693                (Box::new([]), Some(set))
694            };
695        let exempt_prefixes: Box<[String]> = config
696            .get_exempt_prefixes()
697            .iter()
698            .filter(|p: &&String| !p.trim().is_empty())
699            .map(|p: &String| normalize_prefix(p))
700            .collect::<Vec<String>>()
701            .into_boxed_slice();
702        let mut reject_resp: Response = Response::default();
703        reject_resp
704            .set_status_code(config.get_reject_status().code())
705            .set_header(CONTENT_TYPE, config.get_reject_content_type())
706            .set_body(config.get_reject_body().clone());
707        let prebuilt_reject_wire: Vec<u8> = reject_resp.build();
708        Self {
709            config,
710            allowlist,
711            denylist,
712            trusted_proxies,
713            exempt_small,
714            exempt_set,
715            exempt_prefixes,
716            prebuilt_reject_wire,
717        }
718    }
719
720    /// Returns the source [`IpFilterConfig`].
721    ///
722    /// # Returns
723    ///
724    /// - `&IpFilterConfig` - Source configuration.
725    pub fn get_config(&self) -> &IpFilterConfig {
726        let Self { config, .. } = self;
727        config
728    }
729
730    /// Returns the pre-serialized HTTP rejection response wire bytes.
731    ///
732    /// # Returns
733    ///
734    /// - `&Vec<u8>` - Prebuilt wire response buffer.
735    #[inline]
736    pub fn get_prebuilt_reject_wire(&self) -> &Vec<u8> {
737        let Self {
738            prebuilt_reject_wire,
739            ..
740        } = self;
741        prebuilt_reject_wire
742    }
743
744    /// Reports whether `path` is exempted from allowlist/denylist enforcement.
745    ///
746    /// # Arguments
747    ///
748    /// - `&str` - Incoming request path.
749    ///
750    /// # Returns
751    ///
752    /// - `bool` - `true` when exempt.
753    #[inline]
754    pub fn is_path_exempt(&self, path: &str) -> bool {
755        let Self {
756            exempt_small,
757            exempt_set,
758            exempt_prefixes,
759            ..
760        } = self;
761        for exact in exempt_small.iter() {
762            if exact.as_str() == path {
763                return true;
764            }
765        }
766        if let Some(set) = exempt_set
767            && set.contains(path)
768        {
769            return true;
770        }
771        exempt_prefixes
772            .iter()
773            .any(|prefix: &String| path_matches_prefix(path, prefix))
774    }
775
776    /// Resolves the real client IP from `peer_ip` and trusted forwarding headers with zero heap allocations.
777    ///
778    /// Forwarding headers are strictly ignored unless `peer_ip` matches `trusted_proxies`.
779    ///
780    /// # Arguments
781    ///
782    /// - `Option<IpAddr>` - Direct transport peer IP address.
783    /// - `&RequestHeaders` - Incoming request headers.
784    ///
785    /// # Returns
786    ///
787    /// - `Option<ClientIp>` - Resolved client IP metadata.
788    #[inline]
789    pub fn resolve_client_ip(
790        &self,
791        peer_ip: Option<IpAddr>,
792        headers: &RequestHeaders,
793    ) -> Option<ClientIp> {
794        let Self {
795            config,
796            trusted_proxies,
797            ..
798        } = self;
799        let canonical_peer: IpAddr = canonicalize_ip(peer_ip?);
800        if trusted_proxies.is_empty() || !trusted_proxies.contains(canonical_peer) {
801            return Some(ClientIp {
802                ip: canonical_peer,
803                peer_ip: Some(canonical_peer),
804                via_proxy: false,
805            });
806        }
807        let max_hops: usize = config.get_max_trusted_hops();
808        if let Some(xff_vals) = find_header_values(headers, X_FORWARDED_FOR)
809            && let Some(resolved) = peel_xff_right_to_left(xff_vals, trusted_proxies, max_hops)
810        {
811            return Some(ClientIp {
812                ip: resolved,
813                peer_ip: Some(canonical_peer),
814                via_proxy: true,
815            });
816        }
817        if config.get_trust_forwarded_header()
818            && let Some(fwd_vals) = find_header_values(headers, FORWARDED)
819            && let Some(resolved) =
820                peel_forwarded_right_to_left(fwd_vals, trusted_proxies, max_hops)
821        {
822            return Some(ClientIp {
823                ip: resolved,
824                peer_ip: Some(canonical_peer),
825                via_proxy: true,
826            });
827        }
828        if config.get_trust_x_real_ip()
829            && let Some(real_vals) = find_header_values(headers, X_REAL_IP)
830            && let Some(raw_val) = real_vals.back()
831            && let Some(resolved) = parse_forwarded_ip_token(raw_val)
832        {
833            return Some(ClientIp {
834                ip: resolved,
835                peer_ip: Some(canonical_peer),
836                via_proxy: true,
837            });
838        }
839        Some(ClientIp {
840            ip: canonical_peer,
841            peer_ip: Some(canonical_peer),
842            via_proxy: false,
843        })
844    }
845
846    /// Evaluates whether `ip` is permitted by the compiled denylist and allowlist.
847    ///
848    /// Denylist rules always take precedence over allowlist rules.
849    ///
850    /// # Arguments
851    ///
852    /// - `IpAddr` - Resolved client IP.
853    ///
854    /// # Returns
855    ///
856    /// - `bool` - `true` when permitted; `false` when rejected.
857    #[inline]
858    pub fn is_ip_allowed(&self, ip: IpAddr) -> bool {
859        let Self {
860            allowlist,
861            denylist,
862            ..
863        } = self;
864        let canonical: IpAddr = canonicalize_ip(ip);
865        match canonical {
866            IpAddr::V4(v4) => {
867                if !denylist.is_empty() && denylist.contains_v4(v4) {
868                    return false;
869                }
870                if !allowlist.is_empty() && !allowlist.contains_v4(v4) {
871                    return false;
872                }
873            }
874            IpAddr::V6(v6) => {
875                if !denylist.is_empty() && denylist.contains_v6(v6) {
876                    return false;
877                }
878                if !allowlist.is_empty() && !allowlist.contains_v6(v6) {
879                    return false;
880                }
881            }
882        }
883        true
884    }
885
886    /// Resolves `ClientIp`, stores it in `ctx` under [`ATTR_CLIENT_IP`], and enforces allow/deny rules.
887    ///
888    /// # Arguments
889    ///
890    /// - `Option<IpAddr>` - Direct transport peer IP address.
891    /// - `&mut Context` - Incoming request and outgoing response context.
892    ///
893    /// # Returns
894    ///
895    /// - `IpFilterDecision` - Enforcement outcome and resolved client IP metadata.
896    pub fn evaluate(&self, peer_ip: Option<IpAddr>, ctx: &mut Context) -> IpFilterDecision {
897        let Self {
898            allowlist, config, ..
899        } = self;
900        let client_ip: Option<ClientIp> =
901            self.resolve_client_ip(peer_ip, ctx.get_request().get_headers());
902        if let Some(resolved) = client_ip {
903            ctx.set_attribute(ATTR_CLIENT_IP, resolved);
904        }
905        if self.is_path_exempt(ctx.get_request().get_path()) {
906            return IpFilterDecision {
907                action: IpFilterAction::Exempt,
908                client_ip,
909            };
910        }
911        let allowed: bool = match client_ip {
912            Some(resolved) => self.is_ip_allowed(resolved.get_ip()),
913            None => allowlist.is_empty(),
914        };
915        if allowed {
916            return IpFilterDecision {
917                action: IpFilterAction::Allow,
918                client_ip,
919            };
920        }
921        ctx.get_mut_response()
922            .set_status_code(config.get_reject_status().code())
923            .set_header(CONTENT_TYPE, config.get_reject_content_type())
924            .set_body(config.get_reject_body().clone());
925        IpFilterDecision {
926            action: IpFilterAction::Deny,
927            client_ip,
928        }
929    }
930}
931
932/// Process-wide singleton management for [`IpFilterPlugin`].
933impl IpFilterPlugin {
934    /// Initializes the global [`IpFilterPlugin`] once with `config`.
935    ///
936    /// # Arguments
937    ///
938    /// - `IpFilterConfig` - IP extraction and CIDR filtering configuration.
939    ///
940    /// # Returns
941    ///
942    /// - `&'static Self` - Reference to the initialized global plugin.
943    pub fn init(config: IpFilterConfig) -> &'static Self {
944        IP_FILTER_PLUGIN.get_or_init(|| Self {
945            compiled: CompiledIpFilter::compile(config),
946        })
947    }
948
949    /// Returns the initialized global [`IpFilterPlugin`], if [`IpFilterPlugin::init`] was called.
950    ///
951    /// # Returns
952    ///
953    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
954    #[inline]
955    pub fn get() -> Option<&'static Self> {
956        IP_FILTER_PLUGIN.get()
957    }
958
959    /// Returns the compiled [`CompiledIpFilter`] engine.
960    ///
961    /// # Returns
962    ///
963    /// - `&CompiledIpFilter` - Compiled filter engine.
964    #[inline]
965    pub fn get_compiled(&self) -> &CompiledIpFilter {
966        let Self { compiled } = self;
967        compiled
968    }
969}
970
971/// Implements [`ServerHook`] for [`IpFilterHook`].
972impl ServerHook for IpFilterHook {
973    /// Constructs a per-request [`IpFilterHook`].
974    ///
975    /// # Arguments
976    ///
977    /// - `&mut Stream` - Connection stream.
978    /// - `&mut Context` - Request context.
979    ///
980    /// # Returns
981    ///
982    /// - `Self` - Hook instance.
983    async fn new(_: &mut Stream, _: &mut Context) -> Self {
984        Self
985    }
986
987    /// Extracts client IP into `Context` and short-circuits disallowed peers with prebuilt wire bytes.
988    ///
989    /// # Arguments
990    ///
991    /// - `Self` - Hook instance.
992    /// - `&mut Stream` - Connection stream.
993    /// - `&mut Context` - Request context.
994    ///
995    /// # Returns
996    ///
997    /// - `Status` - `Status::Reject` after sending prebuilt rejection bytes; `Status::Continue` otherwise.
998    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
999        let Some(plugin) = IpFilterPlugin::get() else {
1000            return Status::Continue;
1001        };
1002        let compiled: &CompiledIpFilter = plugin.get_compiled();
1003        let peer_ip: Option<IpAddr> = stream
1004            .get_peer_addr()
1005            .ok()
1006            .map(|addr: SocketAddr| addr.ip());
1007        let client_ip: Option<ClientIp> =
1008            compiled.resolve_client_ip(peer_ip, ctx.get_request().get_headers());
1009        if let Some(resolved) = client_ip {
1010            ctx.set_attribute(ATTR_CLIENT_IP, resolved);
1011        }
1012        if compiled.is_path_exempt(ctx.get_request().get_path()) {
1013            return Status::Continue;
1014        }
1015        let allowed: bool = match client_ip {
1016            Some(resolved) => compiled.is_ip_allowed(resolved.get_ip()),
1017            None => compiled.allowlist.is_empty(),
1018        };
1019        if allowed {
1020            return Status::Continue;
1021        }
1022        let _: Result<(), ResponseError> =
1023            stream.try_send(compiled.get_prebuilt_reject_wire()).await;
1024        Status::Reject
1025    }
1026}