footing 0.1.4

Feature-gated foundations for Rust backend services
Documentation
//! Network primitives shared by service configuration and transports.
//!
//! ```rust
//! # #[cfg(feature = "net")]
//! # {
//! use footing::net::{ClientIp, IpNetworkSet};
//!
//! let proxies = IpNetworkSet::from_cidrs(["10.0.0.0/8", " 10.0.0.0/8 "]).unwrap();
//! assert_eq!(proxies.normalized_cidrs(), ["10.0.0.0/8"]);
//!
//! let client_ip = ClientIp::new("\"[2001:db8::1]:443\"").unwrap();
//! assert_eq!(client_ip.as_str(), "2001:db8::1");
//! # }
//! ```

use std::{collections::BTreeMap, fmt, net::IpAddr};

use ipnet::IpNet;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;

use crate::result::{ClassifyError, ErrorKind};

/// Maximum supported client IP length.
pub const MAX_CLIENT_IP_LENGTH: usize = 128;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// Represents client IP.
pub struct ClientIp {
    address: IpAddr,
    display: String,
}

impl ClientIp {
    /// Creates a new instance.
    pub fn new(value: impl AsRef<str>) -> Result<Self, ClientIpError> {
        parse_client_ip_value(value.as_ref()).ok_or(ClientIpError::Invalid)
    }

    /// Attempts to parse and normalize a client IP address.
    pub fn try_new(value: impl AsRef<str>) -> Result<Self, ClientIpError> {
        Self::new(value)
    }

    #[must_use]
    /// Creates a value from IP addr.
    pub fn from_ip_addr(address: IpAddr) -> Self {
        Self {
            address,
            display: address.to_string(),
        }
    }

    #[must_use]
    /// Parses the value.
    pub fn parse(value: &str) -> Option<Self> {
        Self::new(value).ok()
    }

    #[must_use]
    /// Returns this value as IP addr.
    pub fn as_ip_addr(&self) -> IpAddr {
        self.address
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.display
    }
}

impl TryFrom<&str> for ClientIp {
    type Error = ClientIpError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl TryFrom<String> for ClientIp {
    type Error = ClientIpError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl From<IpAddr> for ClientIp {
    fn from(value: IpAddr) -> Self {
        Self::from_ip_addr(value)
    }
}

impl From<ClientIp> for String {
    fn from(value: ClientIp) -> Self {
        value.display
    }
}

impl fmt::Display for ClientIp {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl Serialize for ClientIp {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for ClientIp {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling client IP.
pub enum ClientIpError {
    #[error("client IP is invalid")]
    /// Indicates invalid.
    Invalid,
}

impl ClassifyError for ClientIpError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::Invalid => "client_ip_invalid",
        })
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
/// Represents IP network set.
pub struct IpNetworkSet {
    networks: Vec<IpNet>,
}

impl IpNetworkSet {
    #[must_use]
    /// Creates a new instance.
    pub fn new(networks: impl IntoIterator<Item = IpNet>) -> Self {
        let mut by_cidr = BTreeMap::new();
        for network in networks {
            by_cidr.insert(network.to_string(), network);
        }
        Self {
            networks: by_cidr.into_values().collect(),
        }
    }

    /// Creates a value from CIDRs.
    pub fn from_cidrs(
        cidrs: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Result<Self, IpNetworkSetParseError> {
        let mut networks = Vec::new();
        for cidr in cidrs {
            let value = cidr.as_ref().trim();
            if value.is_empty() {
                return Err(IpNetworkSetParseError::EmptyCidr);
            }
            let network =
                value
                    .parse::<IpNet>()
                    .map_err(|_| IpNetworkSetParseError::InvalidCidr {
                        value: value.to_owned(),
                    })?;
            networks.push(network);
        }
        Ok(Self::new(networks))
    }

    #[must_use]
    /// Returns the networks.
    pub fn networks(&self) -> &[IpNet] {
        &self.networks
    }

    #[must_use]
    /// Consumes this value and returns networks.
    pub fn into_networks(self) -> Vec<IpNet> {
        self.networks
    }

    #[must_use]
    /// Returns the normalized CIDRs.
    pub fn normalized_cidrs(&self) -> Vec<String> {
        self.networks.iter().map(ToString::to_string).collect()
    }

    #[must_use]
    /// Returns whether this value contains the value.
    pub fn contains(&self, ip: IpAddr) -> bool {
        self.networks.iter().any(|network| network.contains(&ip))
    }

    #[must_use]
    /// Returns whether the collection is empty.
    pub fn is_empty(&self) -> bool {
        self.networks.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling IP network set parse.
pub enum IpNetworkSetParseError {
    #[error("CIDR value must not be empty")]
    /// The CIDR is empty.
    EmptyCidr,
    #[error("CIDR value is invalid: {value}")]
    /// The CIDR is invalid.
    InvalidCidr {
        #[doc = "The offending value."]
        value: String,
    },
}

impl ClassifyError for IpNetworkSetParseError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::EmptyCidr => "cidr_empty",
            Self::InvalidCidr { .. } => "cidr_invalid",
        })
    }
}

impl IpNetworkSetParseError {
    #[must_use]
    /// Returns the value.
    pub const fn value(&self) -> Option<&str> {
        match self {
            Self::EmptyCidr => None,
            Self::InvalidCidr { value } => Some(value.as_str()),
        }
    }

    #[must_use]
    /// Returns whether this value is empty CIDR.
    pub const fn is_empty_cidr(&self) -> bool {
        matches!(self, Self::EmptyCidr)
    }
}

fn parse_client_ip_value(value: &str) -> Option<ClientIp> {
    let value = value.trim().trim_matches('"');
    let value = client_ip_host(value)?;
    value.parse::<IpAddr>().ok().map(ClientIp::from_ip_addr)
}

fn client_ip_host(value: &str) -> Option<&str> {
    if value.is_empty() || value.len() > MAX_CLIENT_IP_LENGTH {
        return None;
    }

    if let Some(rest) = value.strip_prefix('[') {
        let (host, suffix) = rest.split_once(']')?;
        if host.is_empty() {
            return None;
        }
        if suffix.is_empty() {
            return Some(host);
        }
        let port = suffix.strip_prefix(':')?;
        return (!port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit()))
            .then_some(host);
    }

    match value.rsplit_once(':') {
        Some((host, port))
            if !host.contains(':')
                && !port.is_empty()
                && port.bytes().all(|byte| byte.is_ascii_digit()) =>
        {
            Some(host)
        }
        _ => Some(value),
    }
}

#[cfg(test)]
mod tests {
    use std::net::IpAddr;

    use super::{ClientIp, ClientIpError, IpNetworkSet, IpNetworkSetParseError};
    use crate::result::{ClassifyError, ErrorKind};

    #[test]
    fn client_ip_normalizes_plain_and_forwarded_values() {
        let ipv4 = ClientIp::new("198.51.100.10:443").expect("client IP should parse");
        assert_eq!(ipv4.as_str(), "198.51.100.10");
        assert_eq!(
            ipv4.as_ip_addr(),
            "198.51.100.10".parse::<IpAddr>().unwrap()
        );

        let ipv6 = ClientIp::new(r#""[2001:db8::1]:443""#).expect("client IP should parse");
        assert_eq!(ipv6.as_str(), "2001:db8::1");
        assert_eq!(ipv6.as_ip_addr(), "2001:db8::1".parse::<IpAddr>().unwrap());
    }

    #[test]
    fn client_ip_rejects_invalid_values() {
        assert!(matches!(
            ClientIp::new("not-an-ip"),
            Err(ClientIpError::Invalid)
        ));
        assert!(matches!(ClientIp::new(""), Err(ClientIpError::Invalid)));
        assert!(matches!(
            ClientIp::new("198.51.100.10:"),
            Err(ClientIpError::Invalid)
        ));
        assert!(matches!(
            ClientIp::new("[2001:db8::1]extra"),
            Err(ClientIpError::Invalid)
        ));
        assert!(matches!(
            ClientIp::new("[2001:db8::1]:https"),
            Err(ClientIpError::Invalid)
        ));
    }

    #[test]
    fn network_errors_are_classified() {
        let client_ip = ClientIp::new("not-an-ip").unwrap_err();
        assert_eq!(client_ip.error_kind(), ErrorKind::Validation);
        assert_eq!(client_ip.error_code(), "client_ip_invalid");

        let cidr = IpNetworkSet::from_cidrs(["not-a-cidr"]).unwrap_err();
        assert_eq!(cidr.error_kind(), ErrorKind::Validation);
        assert_eq!(cidr.error_code(), "cidr_invalid");
    }

    #[test]
    fn network_set_normalizes_sorts_and_deduplicates_cidrs() {
        let set = IpNetworkSet::from_cidrs([
            " 10.0.0.0/8 ",
            "2001:db8::/32",
            "10.0.0.0/8",
            "192.168.0.0/16",
        ])
        .expect("CIDRs should parse");

        assert_eq!(
            set.normalized_cidrs(),
            ["10.0.0.0/8", "192.168.0.0/16", "2001:db8::/32"]
        );
        assert!(set.contains("10.1.2.3".parse::<IpAddr>().unwrap()));
        assert!(!set.contains("172.16.0.1".parse::<IpAddr>().unwrap()));
    }

    #[test]
    fn network_set_rejects_empty_and_invalid_cidrs() {
        assert!(matches!(
            IpNetworkSet::from_cidrs([" "]),
            Err(IpNetworkSetParseError::EmptyCidr)
        ));

        assert!(matches!(
            IpNetworkSet::from_cidrs(["not-a-cidr"]),
            Err(IpNetworkSetParseError::InvalidCidr { value }) if value == "not-a-cidr"
        ));
    }
}