footing 0.1.22

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

use ipnet::IpNet;

use crate::net::IpNetworkSet;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling which peers may supply forwarded headers.
///
/// ```rust
/// use footing::{http::ForwardedHeadersPolicy, net::IpNetworkSet};
///
/// let networks = IpNetworkSet::from_cidrs(["10.0.0.0/8"])?;
/// let policy = ForwardedHeadersPolicy::trusted_proxies(networks);
/// assert!(policy.should_trust(Some("10.1.2.3".parse()?)));
/// assert!(!policy.should_trust(None));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub enum ForwardedHeadersPolicy {
    #[default]
    /// Ignores forwarded headers from every peer; the default policy.
    Never,
    /// Trusts forwarded headers without checking the peer address.
    Always,
    /// Trusts forwarded headers only from peers in these networks.
    TrustedProxies(IpNetworkSet),
}

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]
    /// Trusts forwarded headers only from peers in the supplied network set.
    /// An empty set or a missing peer address grants no trust.
    pub fn trusted_proxies(networks: IpNetworkSet) -> Self {
        Self::TrustedProxies(networks)
    }

    #[must_use]
    /// Trusts only the exact loopback peers `127.0.0.1` and `::1`.
    pub fn local_development() -> Self {
        Self::trusted_proxies(IpNetworkSet::new([
            IpNet::from(IpAddr::V4(Ipv4Addr::LOCALHOST)),
            IpNet::from(IpAddr::V6(Ipv6Addr::LOCALHOST)),
        ]))
    }

    #[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(networks) => peer.is_some_and(|peer| networks.contains(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)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn local_development_trusts_exact_loopback_peers() {
        let policy = ForwardedHeadersPolicy::local_development();
        for peer in ["127.0.0.1", "::1", "::ffff:127.0.0.1"] {
            assert!(policy.should_trust(Some(peer.parse().unwrap())));
        }
        for peer in ["127.0.0.2", "::ffff:127.0.0.2", "192.168.0.1"] {
            assert!(!policy.should_trust(Some(peer.parse().unwrap())));
        }
        assert!(!policy.should_trust(None));
    }

    #[test]
    fn forwarded_headers_policy_trusts_only_configured_proxies() {
        let policy = ForwardedHeadersPolicy::trusted_proxies(
            IpNetworkSet::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!(ForwardedHeadersPolicy::always().should_trust(None));
        for policy in [
            ForwardedHeadersPolicy::default(),
            ForwardedHeadersPolicy::trusted_proxies(IpNetworkSet::default()),
        ] {
            assert!(!policy.should_trust(Some("10.1.2.3".parse().unwrap())));
            assert!(!policy.should_trust(None));
        }
    }
}