capy-core 0.10.0

Typed configuration, application context, and errors for the Capy web framework.
Documentation
use crate::{AppError, Result};
use axum::http::HeaderMap;
use serde::{Deserialize, Serialize};
use std::net::{IpAddr, SocketAddr};

/// Exactly one trusted header convention; no fallback between competing headers.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum ClientIpStrategy {
    /// Ignore all proxy headers and use the socket peer (default).
    #[default]
    Direct,
    /// RFC 7239 `Forwarded`, with numeric `for` addresses.
    Forwarded,
    /// Comma-separated numeric addresses in `X-Forwarded-For`.
    XForwardedFor,
    /// One address in `X-Real-IP`; suitable only for a sanitizing final proxy.
    XRealIp,
}
/// Client identity policy under `[client_ip]` in config/http.toml.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ClientIpSettings {
    /// Socket-only by default.
    pub strategy: ClientIpStrategy,
    /// Explicit IPv4/IPv6 CIDRs. Never trust all networks (`/0`).
    pub trusted_proxies: Vec<String>,
    /// Declare a proxy-only deployment. Reject direct mode at check/startup and
    /// requests from untrusted socket peers at runtime. Default false.
    pub require_proxy: bool,
}
impl ClientIpSettings {
    /// Offline topology validation. Socket metadata is verified on each request;
    /// an offline check cannot infer infrastructure or custom server wiring.
    pub fn validate(&self) -> Result<()> {
        ClientIpResolver::new(self).map(|_| ())
    }
}
#[derive(Clone, Debug)]
struct Network {
    ip: IpAddr,
    prefix: u32,
}
impl Network {
    fn parse(value: &str) -> Option<Self> {
        let (ip, prefix) = value.split_once('/')?;
        let ip: IpAddr = ip.parse().ok()?;
        let prefix: u32 = prefix.parse().ok()?;
        if prefix == 0 || prefix > if ip.is_ipv4() { 32 } else { 128 } {
            return None;
        }
        // Mapped IPv6 networks create ambiguous trust boundaries; use IPv4 CIDRs.
        if matches!(ip, IpAddr::V6(v) if v.to_ipv4_mapped().is_some()) {
            return None;
        }
        Some(Self { ip, prefix })
    }
    fn contains(&self, ip: IpAddr) -> bool {
        match (self.ip, canonical(ip)) {
            (IpAddr::V4(net), IpAddr::V4(ip)) => {
                u32::from(net) >> (32 - self.prefix) == u32::from(ip) >> (32 - self.prefix)
            }
            (IpAddr::V6(net), IpAddr::V6(ip)) => {
                u128::from(net) >> (128 - self.prefix) == u128::from(ip) >> (128 - self.prefix)
            }
            _ => false,
        }
    }
}
fn canonical(ip: IpAddr) -> IpAddr {
    match ip {
        IpAddr::V6(v) => v.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(ip),
        _ => ip,
    }
}
/// Validated, reusable resolver. Forged headers from untrusted peers are ignored.
/// Trusted chains are walked right to left; the first untrusted address is the client.
/// Missing/ambiguous identities fail closed with a generic 503, never a shared bucket.
#[derive(Clone, Debug)]
pub struct ClientIpResolver {
    settings: ClientIpSettings,
    networks: Vec<Network>,
}
impl ClientIpResolver {
    /// Parse trust boundaries once at startup; reject unusable/global trust policies.
    pub fn new(settings: &ClientIpSettings) -> Result<Self> {
        let invalid = || {
            AppError::Configuration("Invalid HTTP client_ip policy: direct mode requires no trusted_proxies and require_proxy=false; proxy strategies require explicit IPv4/IPv6 CIDRs (no /0, at most 64). Configure the actual proxy networks and the header your proxy sanitizes so auth throttling can distinguish clients.".into())
        };
        if settings.trusted_proxies.len() > 64
            || (settings.strategy == ClientIpStrategy::Direct
                && (settings.require_proxy || !settings.trusted_proxies.is_empty()))
            || (settings.strategy != ClientIpStrategy::Direct
                && settings.trusted_proxies.is_empty())
        {
            return Err(invalid());
        }
        let networks = settings
            .trusted_proxies
            .iter()
            .map(|s| Network::parse(s).ok_or_else(invalid))
            .collect::<Result<Vec<_>>>()?;
        Ok(Self {
            settings: settings.clone(),
            networks,
        })
    }
    fn trusted(&self, ip: IpAddr) -> bool {
        self.networks.iter().any(|net| net.contains(ip))
    }
    /// Resolve from the actual socket peer, supplied by the server, and request headers.
    /// Header values, addresses, and request credentials are never logged on failure.
    pub fn resolve(&self, peer: Option<SocketAddr>, headers: &HeaderMap) -> Result<IpAddr> {
        let fail = |reason| {
            tracing::warn!(event = "http.client_ip.unavailable", reason);
            AppError::ClientIdentityUnavailable
        };
        let peer = canonical(peer.ok_or_else(|| fail("missing_peer"))?.ip());
        if peer.is_unspecified() || peer.is_multicast() {
            return Err(fail("invalid_peer"));
        }
        if self.settings.strategy == ClientIpStrategy::Direct {
            return Ok(peer);
        }
        if !self.trusted(peer) {
            return if self.settings.require_proxy {
                Err(fail("untrusted_peer"))
            } else {
                Ok(peer)
            };
        }
        let name = match self.settings.strategy {
            ClientIpStrategy::Forwarded => "forwarded",
            ClientIpStrategy::XForwardedFor => "x-forwarded-for",
            ClientIpStrategy::XRealIp => "x-real-ip",
            ClientIpStrategy::Direct => unreachable!(),
        };
        let mut chain = Vec::new();
        let mut bytes = 0usize;
        for value in headers.get_all(name) {
            bytes = bytes.saturating_add(value.len());
            if bytes > 8192 {
                return Err(fail("header_too_large"));
            }
            let value = value.to_str().map_err(|_| fail("malformed_header"))?;
            for hop in value.split(',') {
                if chain.len() == 32 {
                    return Err(fail("too_many_hops"));
                }
                let ip = if self.settings.strategy == ClientIpStrategy::Forwarded {
                    forwarded(hop)
                } else {
                    hop.trim().parse().ok()
                };
                let ip = canonical(ip.ok_or_else(|| fail("malformed_header"))?);
                if ip.is_unspecified() || ip.is_multicast() {
                    return Err(fail("invalid_address"));
                }
                chain.push(ip);
            }
        }
        if self.settings.strategy == ClientIpStrategy::XRealIp && chain.len() != 1 {
            return Err(fail("ambiguous_header"));
        }
        for ip in chain.into_iter().rev() {
            if !self.trusted(ip) {
                return Ok(ip);
            }
        }
        Err(fail("missing_client_boundary"))
    }
}
fn forwarded(hop: &str) -> Option<IpAddr> {
    let mut address = None;
    for pair in hop.split(';') {
        let (key, value) = pair.trim().split_once('=')?;
        if !key.eq_ignore_ascii_case("for") {
            continue;
        }
        if address.is_some() {
            return None;
        }
        let value = value.trim();
        let value = if value.starts_with('"') {
            value.strip_prefix('"')?.strip_suffix('"')?
        } else {
            value
        };
        let ip = value
            .parse()
            .ok()
            .or_else(|| value.parse::<SocketAddr>().ok().map(|a| a.ip()))
            .or_else(|| value.strip_prefix('[')?.strip_suffix(']')?.parse().ok())?;
        address = Some(ip);
    }
    address
}