hyperlane-plugin-ip-filter 22.14.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::*;

/// Canonicalizes `ip` by converting IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) to IPv4.
///
/// # Arguments
///
/// - `IpAddr` - Raw IPv4 or IPv6 address.
///
/// # Returns
///
/// - `IpAddr` - Canonicalized IP address.
#[inline]
pub fn canonicalize_ip(ip: IpAddr) -> IpAddr {
    match ip {
        IpAddr::V4(v4) => IpAddr::V4(v4),
        IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
            Some(v4) => IpAddr::V4(v4),
            None => IpAddr::V6(v6),
        },
    }
}

/// Computes the 32-bit network mask for an IPv4 CIDR prefix length.
///
/// # Arguments
///
/// - `u8` - Prefix length in `0..=32`.
///
/// # Returns
///
/// - `u32` - High-bit prefix mask.
#[inline]
pub(crate) fn ipv4_prefix_mask(prefix_len: u8) -> u32 {
    if prefix_len == 0 {
        0
    } else if prefix_len >= IPV4_MAX_PREFIX {
        u32::MAX
    } else {
        u32::MAX << (IPV4_MAX_PREFIX - prefix_len)
    }
}

/// Computes the 128-bit network mask for an IPv6 CIDR prefix length.
///
/// # Arguments
///
/// - `u8` - Prefix length in `0..=128`.
///
/// # Returns
///
/// - `u128` - High-bit prefix mask.
#[inline]
pub(crate) fn ipv6_prefix_mask(prefix_len: u8) -> u128 {
    if prefix_len == 0 {
        0
    } else if prefix_len >= IPV6_MAX_PREFIX {
        u128::MAX
    } else {
        u128::MAX << (IPV6_MAX_PREFIX - prefix_len)
    }
}

/// Parses an individual address token from `X-Forwarded-For`, `X-Real-IP`, or RFC 7239 `Forwarded`.
///
/// Strips optional surrounding quotes, IPv6 brackets, and trailing `:port`, then canonicalizes IPv4-mapped IPv6.
///
/// # Arguments
///
/// - `&str` - Raw header address token.
///
/// # Returns
///
/// - `Option<IpAddr>` - Parsed and canonicalized IP address, or `None` when invalid/obfuscated.
pub(crate) fn parse_forwarded_ip_token(raw: &str) -> Option<IpAddr> {
    let trimmed: &str = raw.trim().trim_matches('"').trim();
    if trimmed.is_empty()
        || trimmed.starts_with('_')
        || trimmed.eq_ignore_ascii_case(FORWARDED_UNKNOWN)
    {
        return None;
    }
    if let Some(after_open) = trimmed.strip_prefix('[') {
        let end_bracket: usize = after_open.find(']')?;
        let host: &str = &after_open[..end_bracket];
        return IpAddr::from_str(host).ok().map(canonicalize_ip);
    }
    if let Ok(ip) = IpAddr::from_str(trimmed) {
        return Some(canonicalize_ip(ip));
    }
    if let Ok(sock) = SocketAddr::from_str(trimmed) {
        return Some(canonicalize_ip(sock.ip()));
    }
    None
}

/// Extracts the `for=` value from a single RFC 7239 `Forwarded` element (semicolon-delimited parameters).
///
/// # Arguments
///
/// - `&str` - One comma-separated element of a `Forwarded` header.
///
/// # Returns
///
/// - `Option<IpAddr>` - Parsed canonicalized IP address from the `for=` directive.
pub(crate) fn parse_rfc7239_element_for(element: &str) -> Option<IpAddr> {
    for param in element.split(';') {
        let trimmed: &str = param.trim();
        if trimmed.len() > FORWARDED_FOR_PREFIX.len()
            && trimmed[..FORWARDED_FOR_PREFIX.len()].eq_ignore_ascii_case(FORWARDED_FOR_PREFIX)
        {
            return parse_forwarded_ip_token(&trimmed[FORWARDED_FOR_PREFIX.len()..]);
        }
    }
    None
}

/// Looks up a request header's values slice with an `O(1)` lowercase fast path and case-insensitive fallback.
///
/// # Arguments
///
/// - `&RequestHeaders` - Request header map.
/// - `&str` - Canonical lowercase header name.
///
/// # Returns
///
/// - `Option<&VecDeque<String>>` - Borrowed header value queue if present.
#[inline]
pub(crate) fn find_header_values<'a>(
    headers: &'a RequestHeaders,
    lower_name: &str,
) -> Option<&'a VecDeque<String>> {
    if let Some(vals) = headers.get(lower_name) {
        return Some(vals);
    }
    headers
        .iter()
        .find(|(k, _): &(&String, &VecDeque<String>)| k.eq_ignore_ascii_case(lower_name))
        .map(|(_, v): (&String, &VecDeque<String>)| v)
}

/// Peels trusted proxy hops right-to-left from `X-Forwarded-For` header values without allocating.
///
/// # Arguments
///
/// - `&VecDeque<String>` - All `X-Forwarded-For` header lines in wire order.
/// - `&CidrTable` - Trusted proxy CIDR table.
/// - `usize` - Maximum number of trusted hops to peel.
///
/// # Returns
///
/// - `Option<IpAddr>` - First untrusted IP encountered right-to-left, or the leftmost valid trusted IP.
pub(crate) fn peel_xff_right_to_left(
    values: &VecDeque<String>,
    trusted_proxies: &CidrTable,
    max_hops: usize,
) -> Option<IpAddr> {
    let mut last_valid: Option<IpAddr> = None;
    let mut peeled: usize = 0;
    for header_val in values.iter().rev() {
        for raw_token in header_val.rsplit(',') {
            let trimmed: &str = raw_token.trim();
            if trimmed.is_empty() {
                continue;
            }
            let Some(ip) = parse_forwarded_ip_token(trimmed) else {
                return last_valid;
            };
            last_valid = Some(ip);
            if trusted_proxies.contains(ip) && peeled < max_hops {
                peeled += 1;
                continue;
            }
            return Some(ip);
        }
    }
    last_valid
}

/// Peels trusted proxy hops right-to-left from RFC 7239 `Forwarded` header values without allocating.
///
/// # Arguments
///
/// - `&VecDeque<String>` - All `Forwarded` header lines in wire order.
/// - `&CidrTable` - Trusted proxy CIDR table.
/// - `usize` - Maximum number of trusted hops to peel.
///
/// # Returns
///
/// - `Option<IpAddr>` - First untrusted IP encountered right-to-left, or the leftmost valid trusted IP.
pub(crate) fn peel_forwarded_right_to_left(
    values: &VecDeque<String>,
    trusted_proxies: &CidrTable,
    max_hops: usize,
) -> Option<IpAddr> {
    let mut last_valid: Option<IpAddr> = None;
    let mut peeled: usize = 0;
    for header_val in values.iter().rev() {
        for element in header_val.rsplit(',') {
            let trimmed: &str = element.trim();
            if trimmed.is_empty() {
                continue;
            }
            let Some(ip) = parse_rfc7239_element_for(trimmed) else {
                return last_valid;
            };
            last_valid = Some(ip);
            if trusted_proxies.contains(ip) && peeled < max_hops {
                peeled += 1;
                continue;
            }
            return Some(ip);
        }
    }
    last_valid
}

/// Normalizes a path prefix by stripping trailing slashes while keeping `"/"` intact.
///
/// # Arguments
///
/// - `&str` - Raw path prefix.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(prefix: &str) -> String {
    let trimmed: &str = prefix.trim();
    if trimmed == "/" {
        return "/".to_owned();
    }
    let stripped: &str = trimmed.trim_end_matches('/');
    if stripped.is_empty() {
        "/".to_owned()
    } else {
        stripped.to_owned()
    }
}

/// Checks whether `path` matches normalized `prefix` on a URL segment boundary.
///
/// # Arguments
///
/// - `&str` - Request path.
/// - `&str` - Normalized path prefix.
///
/// # Returns
///
/// - `bool` - `true` when `path` equals `prefix` or starts with `prefix` followed by `'/'`.
#[inline]
pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    if prefix == "/" {
        return true;
    }
    let Some(rest) = path.strip_prefix(prefix) else {
        return false;
    };
    rest.is_empty() || rest.starts_with('/')
}