ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! Trusted proxies and the [`ClientIp`] extractor.
//!
//! Forwarding headers are honored only when the TCP peer is a trusted proxy, so a client
//! cannot spoof its address by sending `X-Forwarded-For` itself.
use axum::{
    extract::{ConnectInfo, FromRequestParts},
    http::request::Parts,
};
use std::{
    convert::Infallible,
    net::{IpAddr, SocketAddr},
};

/// Set of proxy addresses (IPs and CIDR ranges) allowed to speak for the client. Empty trusts nobody.
///
/// ```
/// let p = ryuk::proxy::TrustedProxies::parse("10.0.0.0/8, 192.168.1.5").unwrap();
/// assert!(p.contains("10.1.2.3".parse().unwrap()));
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TrustedProxies(Vec<(IpAddr, u8)>);

impl TrustedProxies {
    /// Parses a comma-separated list of IPs and CIDRs; a malformed entry is an error.
    pub fn parse(s: &str) -> Result<Self, String> {
        let mut v = vec![];
        for item in s.split(',').map(str::trim).filter(|i| !i.is_empty()) {
            let (ip, bits) = item.split_once('/').unwrap_or((item, ""));
            let ip: IpAddr = ip
                .parse()
                .map_err(|_| format!("TRUSTED_PROXIES: `{item}` is not an IP or CIDR"))?;
            let max = if ip.is_ipv4() { 32 } else { 128 };
            let bits = if bits.is_empty() {
                max
            } else {
                bits.parse::<u8>()
                    .ok()
                    .filter(|b| *b <= max)
                    .ok_or(format!("TRUSTED_PROXIES: bad prefix length in `{item}`"))?
            };
            v.push((ip.to_canonical(), bits));
        }
        Ok(TrustedProxies(v))
    }

    /// Reads `TRUSTED_PROXIES` (unset = trust nobody).
    pub fn from_env() -> Result<Self, String> {
        Self::parse(&std::env::var("TRUSTED_PROXIES").unwrap_or_default())
    }

    /// True when nobody is trusted.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Whether `ip` is inside any trusted entry.
    pub fn contains(&self, ip: IpAddr) -> bool {
        let ip = ip.to_canonical();
        self.0.iter().any(|&(net, bits)| match (net, ip) {
            (IpAddr::V4(n), IpAddr::V4(i)) => {
                same_prefix(u32::from(n) as u128, u32::from(i) as u128, bits, 32)
            }
            (IpAddr::V6(n), IpAddr::V6(i)) => same_prefix(u128::from(n), u128::from(i), bits, 128),
            _ => false,
        })
    }
}

fn same_prefix(a: u128, b: u128, bits: u8, width: u8) -> bool {
    let shift = (width - bits) as u32;
    shift >= 128 || (a >> shift) == (b >> shift)
}

/// Rate-limit bucket for a client: the address for IPv4 (and IPv4-mapped IPv6), the /64 prefix for IPv6,
/// because one subscriber usually owns a whole /64 and could otherwise rotate addresses to dodge limits.
///
/// ```
/// use ryuk::proxy::ip_bucket;
/// assert_eq!(ip_bucket("::ffff:1.2.3.4".parse().unwrap()), "1.2.3.4");
/// assert_eq!(ip_bucket("2001:db8:1:2:aaaa::1".parse().unwrap()), "2001:db8:1:2::/64");
/// ```
pub fn ip_bucket(ip: IpAddr) -> String {
    match ip.to_canonical() {
        IpAddr::V4(v) => v.to_string(),
        IpAddr::V6(v) => {
            let s = v.segments();
            format!("{:x}:{:x}:{:x}:{:x}::/64", s[0], s[1], s[2], s[3])
        }
    }
}

/// The real client address, resolved safely. Needs `TrustedProxies` as a request extension
/// (`App` installs it) and connect info (`App::serve` does); without them it is the peer or `None`.
///
/// ```no_run
/// async fn who(ryuk::proxy::ClientIp(ip): ryuk::proxy::ClientIp) -> String { format!("{ip:?}") }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClientIp(pub Option<IpAddr>);

impl<S: Send + Sync> FromRequestParts<S> for ClientIp {
    type Rejection = Infallible;

    async fn from_request_parts(p: &mut Parts, _: &S) -> Result<Self, Infallible> {
        let peer = p
            .extensions
            .get::<ConnectInfo<SocketAddr>>()
            .map(|c| c.0.ip().to_canonical());
        let (Some(peer), Some(trusted)) = (peer, p.extensions.get::<TrustedProxies>()) else {
            return Ok(ClientIp(peer));
        };
        if !trusted.contains(peer) {
            return Ok(ClientIp(Some(peer)));
        }
        // The right-most hop a trusted proxy did not vouch for is the real client.
        let hops = p
            .headers
            .get_all("x-forwarded-for")
            .iter()
            .filter_map(|v| v.to_str().ok())
            .flat_map(|v| v.split(','))
            .collect::<Vec<_>>();
        for hop in hops.iter().rev() {
            match hop.trim().parse::<IpAddr>() {
                Ok(ip) if trusted.contains(ip) => continue,
                Ok(ip) => return Ok(ClientIp(Some(ip.to_canonical()))),
                Err(_) => break, // garbage hop: stop trusting the chain
            }
        }
        let real = p
            .headers
            .get("x-real-ip")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.trim().parse::<IpAddr>().ok());
        Ok(ClientIp(Some(real.map_or(peer, |i| i.to_canonical()))))
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn ip_bucket_groups_v6_slash64() {
        let b = |s: &str| super::ip_bucket(s.parse().unwrap());
        assert_eq!(b("2001:db8:1:2::1"), b("2001:db8:1:2:ffff:ffff:ffff:ffff"));
        assert_ne!(b("2001:db8:1:2::1"), b("2001:db8:1:3::1"));
        assert_eq!(b("::ffff:10.1.2.3"), "10.1.2.3");
        assert_eq!(b("10.1.2.3"), "10.1.2.3");
    }

    use super::*;
    use axum::http::Request;

    async fn ip(trusted: &str, peer: &str, headers: &[(&str, &str)]) -> String {
        let mut r = Request::get("/");
        for (k, v) in headers {
            r = r.header(*k, *v);
        }
        let mut r = r.body(()).unwrap();
        r.extensions_mut()
            .insert(ConnectInfo(SocketAddr::new(peer.parse().unwrap(), 4000)));
        r.extensions_mut()
            .insert(TrustedProxies::parse(trusted).unwrap());
        let (mut parts, _) = r.into_parts();
        ClientIp::from_request_parts(&mut parts, &())
            .await
            .unwrap()
            .0
            .unwrap()
            .to_string()
    }

    #[tokio::test]
    async fn untrusted_peer_cannot_spoof() {
        assert_eq!(
            ip("", "9.9.9.9", &[("x-forwarded-for", "1.1.1.1")]).await,
            "9.9.9.9"
        );
        assert_eq!(
            ip(
                "10.0.0.0/8",
                "9.9.9.9",
                &[("x-forwarded-for", "1.1.1.1"), ("x-real-ip", "2.2.2.2")]
            )
            .await,
            "9.9.9.9"
        );
    }

    #[tokio::test]
    async fn trusted_peer_uses_rightmost_untrusted() {
        let t = "10.0.0.0/8";
        assert_eq!(
            ip(t, "10.0.0.1", &[("x-forwarded-for", "1.1.1.1")]).await,
            "1.1.1.1"
        );
        // the client-supplied 6.6.6.6 sits left of the real client, so it is ignored
        assert_eq!(
            ip(
                t,
                "10.0.0.1",
                &[("x-forwarded-for", "6.6.6.6, 1.1.1.1, 10.0.0.2")]
            )
            .await,
            "1.1.1.1"
        );
        assert_eq!(
            ip(
                t,
                "10.0.0.1",
                &[
                    ("x-forwarded-for", "6.6.6.6"),
                    ("x-forwarded-for", "1.1.1.1")
                ]
            )
            .await,
            "1.1.1.1"
        );
        assert_eq!(
            ip(
                t,
                "10.0.0.1",
                &[("x-forwarded-for", "10.0.0.5"), ("x-real-ip", "3.3.3.3")]
            )
            .await,
            "3.3.3.3"
        );
        assert_eq!(ip(t, "10.0.0.1", &[]).await, "10.0.0.1");
        assert_eq!(
            ip(t, "10.0.0.1", &[("x-forwarded-for", "nope")]).await,
            "10.0.0.1"
        );
    }

    #[test]
    fn cidr_and_errors() {
        let p = TrustedProxies::parse("10.0.0.0/8,192.168.1.5,fd00::/8").unwrap();
        assert!(
            p.contains("10.255.0.1".parse().unwrap()) && p.contains("fd12::1".parse().unwrap())
        );
        assert!(p.contains("192.168.1.5".parse().unwrap()));
        assert!(
            !p.contains("192.168.1.6".parse().unwrap()) && !p.contains("11.0.0.1".parse().unwrap())
        );
        assert!(
            TrustedProxies::parse("0.0.0.0/0")
                .unwrap()
                .contains("8.8.8.8".parse().unwrap())
        );
        assert!(
            TrustedProxies::parse("10.0.0.0/33").is_err() && TrustedProxies::parse("x").is_err()
        );
        assert!(TrustedProxies::parse("").unwrap().is_empty());
    }
}