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
use super::*;

/// Resolved client IP metadata stored in Hyperlane [`Context`] under [`ATTR_CLIENT_IP`].
#[derive(Clone, Copy, Data, Debug, Eq, PartialEq)]
pub struct ClientIp {
    /// Canonicalized client IP (IPv4-mapped IPv6 addresses are normalized to IPv4).
    #[get(type(copy))]
    pub(crate) ip: IpAddr,
    /// Canonicalized direct TCP peer IP address, when available from the transport stream.
    #[get(type(copy))]
    pub(crate) peer_ip: Option<IpAddr>,
    /// `true` when `ip` was peeled from a trusted proxy forwarding header.
    #[get(type(copy))]
    pub(crate) via_proxy: bool,
}

/// Outcome of evaluating a request through [`CompiledIpFilter`].
#[derive(Clone, Copy, Data, Debug, Eq, PartialEq)]
pub struct IpFilterDecision {
    /// Whether the request was allowed, denied, or skipped via path exemption.
    #[get(type(copy))]
    pub(crate) action: IpFilterAction,
    /// Resolved client IP metadata, when an address could be determined.
    #[get(type(copy))]
    pub(crate) client_ip: Option<ClientIp>,
}

/// User-facing configuration for [`IpFilterPlugin`] and [`CompiledIpFilter`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct IpFilterConfig {
    /// Allowed CIDR networks (empty allows all IPs not matching `denylist`).
    pub(crate) allowlist: Vec<IpNet>,
    /// Denied CIDR networks (always evaluated before `allowlist`).
    pub(crate) denylist: Vec<IpNet>,
    /// Trusted proxy CIDRs permitted to supply forwarding headers.
    pub(crate) trusted_proxies: Vec<IpNet>,
    /// Maximum trusted proxy hops peeled right-to-left before stopping.
    #[get(type(copy))]
    pub(crate) max_trusted_hops: usize,
    /// Whether RFC 7239 `Forwarded` (`for=...`) is inspected when `X-Forwarded-For` is absent.
    #[get(type(copy))]
    pub(crate) trust_forwarded_header: bool,
    /// Whether `X-Real-IP` is inspected as a fallback when `X-Forwarded-For` and `Forwarded` are absent.
    #[get(type(copy))]
    pub(crate) trust_x_real_ip: bool,
    /// Exact request paths exempt from allowlist/denylist rejection.
    pub(crate) exempt_paths: Vec<String>,
    /// Segment-bounded path prefixes exempt from allowlist/denylist rejection.
    pub(crate) exempt_prefixes: Vec<String>,
    /// HTTP status code emitted on rejected requests (default `403 Forbidden`).
    #[get(type(copy))]
    pub(crate) reject_status: HttpStatus,
    /// `Content-Type` header emitted on rejected requests.
    pub(crate) reject_content_type: String,
    /// Response body bytes emitted on rejected requests.
    pub(crate) reject_body: Vec<u8>,
}

/// Flat CSR `/8` radix table of sorted disjoint IPv4 `(start, end)` intervals.
#[derive(Clone, Debug)]
pub(crate) struct V4CidrCsr {
    /// 256-bit bitmap marking IPv4 `/8` blocks fully covered (`O(1)` single bit test).
    pub(crate) full_slash8: [u64; 4],
    /// Bucket boundary offsets (`offsets[b]..offsets[b + 1]`).
    pub(crate) offsets: Box<[u32; CIDR_OFFSET_LEN]>,
    /// Contiguous sorted disjoint IPv4 intervals across all `/8` buckets.
    pub(crate) intervals: Box<[(u32, u32)]>,
}

/// Flat CSR `/8` radix table of sorted disjoint IPv6 `(start, end)` intervals.
#[derive(Clone, Debug)]
pub(crate) struct V6CidrCsr {
    /// 256-bit bitmap marking IPv6 `/8` blocks fully covered (`O(1)` single bit test).
    pub(crate) full_slash8: [u64; 4],
    /// Bucket boundary offsets (`offsets[b]..offsets[b + 1]`).
    pub(crate) offsets: Box<[u32; CIDR_OFFSET_LEN]>,
    /// Contiguous sorted disjoint IPv6 intervals across all `/8` buckets.
    pub(crate) intervals: Box<[(u128, u128)]>,
}

/// Zero-allocation `/8` radix-indexed IPv4/IPv6 CIDR lookup table using merged disjoint intervals.
#[derive(Clone, Debug)]
pub struct CidrTable {
    /// Compiled IPv4 CIDR lookup index (inline for small tables, `/8` CSR radix for large tables).
    pub(crate) v4: V4CidrIndex,
    /// Compiled IPv6 CIDR lookup index (inline for small tables, `/8` CSR radix for large tables).
    pub(crate) v6: V6CidrIndex,
    /// Total number of source CIDR entries compiled into this table.
    pub(crate) entry_count: usize,
}

/// Precompiled zero-allocation IP filter engine backing [`IpFilterPlugin`].
#[derive(Clone, Debug)]
pub struct CompiledIpFilter {
    /// Original configuration retained for inspection.
    pub(crate) config: IpFilterConfig,
    /// Compiled CIDR allowlist (`is_empty()` means allow-all).
    pub(crate) allowlist: CidrTable,
    /// Compiled CIDR denylist (checked first).
    pub(crate) denylist: CidrTable,
    /// Compiled trusted proxy CIDR table.
    pub(crate) trusted_proxies: CidrTable,
    /// Small inline exact exempt path list used when `len <= EXEMPT_SET_THRESHOLD`.
    pub(crate) exempt_small: Box<[String]>,
    /// Exact exempt paths in an `O(1)` `XxHash3_64` hash set when `len > EXEMPT_SET_THRESHOLD`.
    pub(crate) exempt_set: Option<HashSetXxHash3_64<String>>,
    /// Normalized exempt path prefixes.
    pub(crate) exempt_prefixes: Box<[String]>,
    /// Pre-serialized HTTP rejection response wire bytes sent without allocating.
    pub(crate) prebuilt_reject_wire: Vec<u8>,
}

/// Process-wide [`IpFilterPlugin`] singleton holding a compiled [`CompiledIpFilter`].
#[derive(Clone, Debug)]
pub struct IpFilterPlugin {
    /// Precompiled IP filter engine.
    pub(crate) compiled: CompiledIpFilter,
}

/// Opt-in request middleware extracting real client IP and enforcing CIDR allow/deny rules.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::request_middleware(-125)]
pub struct IpFilterHook;