a2a_protocol_server/rate_limit/
trusted.rs1use std::fmt;
18use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
19use std::str::FromStr;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub struct TrustedProxy {
31 net: IpAddr,
32 prefix: u8,
33}
34
35impl TrustedProxy {
36 #[must_use]
41 pub fn new(net: IpAddr, prefix: u8) -> Option<Self> {
42 let (net, prefix) = match net {
43 IpAddr::V6(v6) if prefix >= 96 => v6
46 .to_ipv4_mapped()
47 .map_or((net, prefix), |v4| (IpAddr::V4(v4), prefix - 96)),
48 other => (other, prefix),
49 };
50 let longest = if net.is_ipv4() { 32 } else { 128 };
51 (prefix <= longest).then(|| Self {
52 net: masked(net, prefix),
53 prefix,
54 })
55 }
56
57 #[must_use]
59 pub fn contains(&self, ip: IpAddr) -> bool {
60 let ip = ip.to_canonical();
61 ip.is_ipv4() == self.net.is_ipv4() && masked(ip, self.prefix) == self.net
62 }
63}
64
65fn masked(ip: IpAddr, prefix: u8) -> IpAddr {
67 match ip {
68 IpAddr::V4(v4) => {
69 let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0);
70 IpAddr::V4(Ipv4Addr::from(u32::from(v4) & mask))
71 }
72 IpAddr::V6(v6) => {
73 let mask = u128::MAX.checked_shl(128 - u32::from(prefix)).unwrap_or(0);
74 IpAddr::V6(Ipv6Addr::from(u128::from(v6) & mask))
75 }
76 }
77}
78
79impl fmt::Display for TrustedProxy {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 write!(f, "{}/{}", self.net, self.prefix)
82 }
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct InvalidTrustedProxy(String);
88
89impl fmt::Display for InvalidTrustedProxy {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 write!(f, "not a trusted proxy range: {}", self.0)
92 }
93}
94
95impl std::error::Error for InvalidTrustedProxy {}
96
97impl FromStr for TrustedProxy {
98 type Err = InvalidTrustedProxy;
99
100 fn from_str(s: &str) -> Result<Self, Self::Err> {
101 let bad = |why: &str| InvalidTrustedProxy(format!("{s:?}: {why}"));
102 let (addr, prefix) = match s.split_once('/') {
103 Some((addr, prefix)) => (addr, Some(prefix)),
104 None => (s, None),
105 };
106 let net: IpAddr = addr.parse().map_err(|_| bad("not an IP address"))?;
107 let prefix = match prefix {
108 Some(p) => p.parse::<u8>().map_err(|_| bad("not a prefix length"))?,
109 None if net.is_ipv4() => 32,
110 None => 128,
111 };
112 Self::new(net, prefix).ok_or_else(|| bad("prefix longer than the address"))
113 }
114}
115
116#[cfg(test)]
117mod tests;