footing 0.1.0

Feature-gated foundations for Rust backend services
Documentation
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

use ipnet::IpNet;

use crate::net::{IpNetworkSet, IpNetworkSetParseError};

#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling forwarded headers.
pub enum ForwardedHeadersPolicy {
    #[default]
    /// Indicates never.
    Never,
    /// Indicates always.
    Always,
    /// Indicates trusted proxies.
    TrustedProxies(TrustedProxyConfig),
}

impl ForwardedHeadersPolicy {
    #[must_use]
    /// Creates never.
    pub const fn never() -> Self {
        Self::Never
    }

    #[must_use]
    /// Creates always.
    pub const fn always() -> Self {
        Self::Always
    }

    #[must_use]
    /// Creates trusted proxies.
    pub fn trusted_proxies(config: TrustedProxyConfig) -> Self {
        Self::TrustedProxies(config)
    }

    #[must_use]
    /// Returns whether this value should trust.
    pub fn should_trust(&self, peer: Option<IpAddr>) -> bool {
        match self {
            Self::Never => false,
            Self::Always => true,
            Self::TrustedProxies(config) => config.should_trust_forwarded_headers(peer),
        }
    }

    #[must_use]
    /// Returns the trusts any peer.
    pub const fn trusts_any_peer(&self) -> bool {
        matches!(self, Self::Always)
    }

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

#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
/// Validated configuration for trusted proxy.
pub struct TrustedProxyConfig {
    trusted_proxies: IpNetworkSet,
}

impl TrustedProxyConfig {
    #[must_use]
    /// Creates a new instance.
    pub fn new(trusted_proxies: impl IntoIterator<Item = IpNet>) -> Self {
        Self {
            trusted_proxies: IpNetworkSet::new(trusted_proxies),
        }
    }

    #[must_use]
    /// Creates a value from network set.
    pub fn from_network_set(trusted_proxies: IpNetworkSet) -> Self {
        Self { trusted_proxies }
    }

    /// Creates a value from CIDRs.
    pub fn from_cidrs(
        cidrs: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Result<Self, IpNetworkSetParseError> {
        Ok(Self::from_network_set(IpNetworkSet::from_cidrs(cidrs)?))
    }

    #[must_use]
    /// Creates local development.
    pub fn local_development() -> Self {
        Self::new([
            IpNet::from(IpAddr::V4(Ipv4Addr::LOCALHOST)),
            IpNet::from(IpAddr::V6(Ipv6Addr::LOCALHOST)),
        ])
    }

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

    #[must_use]
    /// Returns the normalized CIDRs.
    pub fn normalized_cidrs(&self) -> Vec<String> {
        self.trusted_proxies.normalized_cidrs()
    }

    #[must_use]
    /// Returns whether this value is trusted.
    pub fn is_trusted(&self, peer: IpAddr) -> bool {
        self.trusted_proxies.contains(peer)
    }

    #[must_use]
    /// Returns whether this value should trust forwarded headers.
    pub fn should_trust_forwarded_headers(&self, peer: Option<IpAddr>) -> bool {
        peer.is_some_and(|peer| self.is_trusted(peer))
    }
}

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

    use super::TrustedProxyConfig;

    #[test]
    fn trusted_proxy_config_matches_cidrs() {
        let config = TrustedProxyConfig::from_cidrs(["10.0.0.0/8"]).unwrap();

        assert!(config.is_trusted("10.1.2.3".parse::<IpAddr>().unwrap()));
        assert!(!config.is_trusted("192.168.1.1".parse::<IpAddr>().unwrap()));
    }

    #[test]
    fn local_development_trusts_exact_loopback_peers() {
        let config = TrustedProxyConfig::local_development();

        assert_eq!(config.normalized_cidrs(), ["127.0.0.1/32", "::1/128"]);
        assert!(config.is_trusted("127.0.0.1".parse::<IpAddr>().unwrap()));
        assert!(config.is_trusted("::1".parse::<IpAddr>().unwrap()));
        assert!(!config.is_trusted("127.0.0.2".parse::<IpAddr>().unwrap()));
    }

    #[test]
    fn forwarded_headers_policy_trusts_only_configured_proxies() {
        let policy = super::ForwardedHeadersPolicy::trusted_proxies(
            TrustedProxyConfig::from_cidrs(["10.0.0.0/8"]).unwrap(),
        );

        assert!(policy.should_trust(Some("10.1.2.3".parse::<IpAddr>().unwrap())));
        assert!(!policy.should_trust(Some("192.168.1.1".parse::<IpAddr>().unwrap())));
        assert!(!policy.should_trust(None));
        assert!(super::ForwardedHeadersPolicy::always().should_trust(None));
        assert!(
            !super::ForwardedHeadersPolicy::never()
                .should_trust(Some("10.1.2.3".parse::<IpAddr>().unwrap()))
        );
    }
}