Skip to main content

arks_server/
proxy.rs

1//! Trusted reverse-proxy CIDR matching and RFC 7239 `Forwarded` / `X-Forwarded-*`
2//! client resolution (governed by `serve-operations.sot.md` SO-PRX-1).
3//!
4//! Forwarding headers are honored **only** when the TCP peer address belongs to a
5//! configured trusted proxy CIDR. Untrusted peers cannot spoof client IP, scheme, or host.
6
7use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
8
9/// A single IPv4 or IPv6 CIDR network range.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum IpCidr {
12    V4 { net: u32, mask: u32 },
13    V6 { net: u128, mask: u128 },
14}
15
16impl IpCidr {
17    /// Parse `"10.0.0.0/8"`, `"127.0.0.1"`, `"::1/128"`, or `"fc00::/7"`.
18    pub fn parse(raw: &str) -> Option<Self> {
19        let s = raw.trim();
20        if s.is_empty() {
21            return None;
22        }
23        let (addr_str, prefix_opt) = match s.split_once('/') {
24            Some((a, p)) => (a.trim(), Some(p.trim())),
25            None => (s, None),
26        };
27        let ip: IpAddr = addr_str.parse().ok()?;
28        match ip {
29            IpAddr::V4(v4) => {
30                let prefix: u32 = match prefix_opt {
31                    Some(p) => p.parse().ok()?,
32                    None => 32,
33                };
34                if prefix > 32 {
35                    return None;
36                }
37                let mask = if prefix == 0 {
38                    0
39                } else {
40                    !0u32 << (32 - prefix)
41                };
42                Some(Self::V4 {
43                    net: u32::from(v4) & mask,
44                    mask,
45                })
46            }
47            IpAddr::V6(v6) => {
48                let prefix: u32 = match prefix_opt {
49                    Some(p) => p.parse().ok()?,
50                    None => 128,
51                };
52                if prefix > 128 {
53                    return None;
54                }
55                let mask = if prefix == 0 {
56                    0
57                } else {
58                    !0u128 << (128 - prefix)
59                };
60                Some(Self::V6 {
61                    net: u128::from(v6) & mask,
62                    mask,
63                })
64            }
65        }
66    }
67
68    pub fn contains(&self, ip: IpAddr) -> bool {
69        match (*self, ip) {
70            (Self::V4 { net, mask }, IpAddr::V4(v4)) => (u32::from(v4) & mask) == net,
71            (Self::V6 { net, mask }, IpAddr::V6(v6)) => (u128::from(v6) & mask) == net,
72            (Self::V4 { net, mask }, IpAddr::V6(v6)) => v6
73                .to_ipv4_mapped()
74                .is_some_and(|v4| (u32::from(v4) & mask) == net),
75            _ => false,
76        }
77    }
78}
79
80/// Configured set of trusted reverse proxies.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct TrustedProxyConfig {
83    cidrs: Vec<IpCidr>,
84}
85
86impl Default for TrustedProxyConfig {
87    /// By default, only local loopback (`127.0.0.1/32`, `::1/128`) is trusted as a reverse proxy.
88    /// Remote peers cannot spoof `Forwarded` or `X-Forwarded-*` headers unless explicitly listed.
89    fn default() -> Self {
90        Self::loopback_only()
91    }
92}
93
94impl TrustedProxyConfig {
95    /// Trust no proxies (ignore all forwarding headers even from loopback).
96    pub fn none() -> Self {
97        Self { cidrs: Vec::new() }
98    }
99
100    /// Trust only local loopback proxies (`127.0.0.1/32` and `::1/128`).
101    pub fn loopback_only() -> Self {
102        Self {
103            cidrs: vec![
104                IpCidr::V4 {
105                    net: u32::from(Ipv4Addr::LOCALHOST),
106                    mask: !0u32,
107                },
108                IpCidr::V6 {
109                    net: u128::from(Ipv6Addr::LOCALHOST),
110                    mask: !0u128,
111                },
112            ],
113        }
114    }
115
116    /// Parse comma-separated CIDRs (e.g. `"127.0.0.1/32,10.0.0.0/8,::1/128"`).
117    pub fn parse_list(csv: &str) -> Self {
118        let cidrs = csv.split(',').filter_map(IpCidr::parse).collect();
119        Self { cidrs }
120    }
121
122    /// Load from `ARKS_TRUSTED_PROXIES` environment variable if set; otherwise loopback-only.
123    /// Setting `ARKS_TRUSTED_PROXIES=""` or `"none"` trusts zero proxies.
124    pub fn from_env() -> Self {
125        match std::env::var("ARKS_TRUSTED_PROXIES") {
126            Ok(val) => {
127                let t = val.trim();
128                if t.is_empty() || t.eq_ignore_ascii_case("none") {
129                    Self::none()
130                } else {
131                    Self::parse_list(t)
132                }
133            }
134            Err(_) => Self::loopback_only(),
135        }
136    }
137
138    pub fn is_trusted(&self, ip: IpAddr) -> bool {
139        self.cidrs.iter().any(|c| c.contains(ip))
140    }
141}
142
143/// Client identity resolved from TCP peer and (when trusted) proxy headers.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct ResolvedClient {
146    pub ip: IpAddr,
147    pub proto: Option<String>,
148    pub host: Option<String>,
149}
150
151/// Resolve effective client IP, scheme, and host from TCP `peer_ip` and request `headers`
152/// (ASCII-lowercase keys).
153///
154/// Honors RFC 7239 `Forwarded` first, falling back to `X-Forwarded-For` / `X-Forwarded-Proto`
155/// / `X-Forwarded-Host`, **only** when `cfg.is_trusted(peer_ip)` is `true`.
156pub fn resolve_client(
157    peer_ip: IpAddr,
158    headers: &[(String, String)],
159    cfg: &TrustedProxyConfig,
160) -> ResolvedClient {
161    if !cfg.is_trusted(peer_ip) {
162        return ResolvedClient {
163            ip: peer_ip,
164            proto: None,
165            host: None,
166        };
167    }
168
169    // 1. Prefer RFC 7239 `Forwarded` header when present.
170    if let Some(fwd) = find_header(headers, "forwarded") {
171        let parsed = parse_rfc7239_forwarded(fwd, peer_ip, cfg);
172        return parsed;
173    }
174
175    // 2. Fallback to `X-Forwarded-For`, `X-Forwarded-Proto`, `X-Forwarded-Host`.
176    let ip = find_header(headers, "x-forwarded-for")
177        .and_then(|xff| rightmost_untrusted_ip(xff, cfg))
178        .unwrap_or(peer_ip);
179    let proto = find_header(headers, "x-forwarded-proto")
180        .and_then(|v| v.split(',').next())
181        .map(|s| s.trim().to_ascii_lowercase())
182        .filter(|s| s == "http" || s == "https");
183    let host = find_header(headers, "x-forwarded-host")
184        .and_then(|v| v.split(',').next())
185        .map(|s| s.trim().to_string())
186        .filter(|s| !s.is_empty());
187
188    ResolvedClient { ip, proto, host }
189}
190
191fn find_header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
192    headers
193        .iter()
194        .find(|(k, _)| k.eq_ignore_ascii_case(name))
195        .map(|(_, v)| v.as_str())
196}
197
198fn rightmost_untrusted_ip(xff: &str, cfg: &TrustedProxyConfig) -> Option<IpAddr> {
199    let ips: Vec<IpAddr> = xff
200        .split(',')
201        .filter_map(|part| parse_forwarded_ip(part.trim()))
202        .collect();
203    if ips.is_empty() {
204        return None;
205    }
206    // Walk right-to-left skipping trusted proxies; return the first untrusted client IP.
207    for &ip in ips.iter().rev() {
208        if !cfg.is_trusted(ip) {
209            return Some(ip);
210        }
211    }
212    ips.first().copied()
213}
214
215/// Parse RFC 7239 `Forwarded: for=192.0.2.60;proto=https;host=example.com` (may contain
216/// comma-separated hop entries; uses the first hop's `proto`/`host` and rightmost untrusted `for`).
217fn parse_rfc7239_forwarded(raw: &str, peer_ip: IpAddr, cfg: &TrustedProxyConfig) -> ResolvedClient {
218    let mut for_ips: Vec<IpAddr> = Vec::new();
219    let mut proto: Option<String> = None;
220    let mut host: Option<String> = None;
221
222    for hop in raw.split(',') {
223        for param in hop.split(';') {
224            let Some((k, v)) = param.split_once('=') else {
225                continue;
226            };
227            let key = k.trim().to_ascii_lowercase();
228            let val = v.trim().trim_matches('"');
229            match key.as_str() {
230                "for" => {
231                    if let Some(ip) = parse_forwarded_ip(val) {
232                        for_ips.push(ip);
233                    }
234                }
235                "proto" if proto.is_none() => {
236                    let p = val.to_ascii_lowercase();
237                    if p == "http" || p == "https" {
238                        proto = Some(p);
239                    }
240                }
241                "host" if host.is_none() && !val.is_empty() => {
242                    host = Some(val.to_string());
243                }
244                _ => {}
245            }
246        }
247    }
248
249    let ip = for_ips
250        .iter()
251        .rev()
252        .copied()
253        .find(|&ip| !cfg.is_trusted(ip))
254        .or_else(|| for_ips.first().copied())
255        .unwrap_or(peer_ip);
256
257    ResolvedClient { ip, proto, host }
258}
259
260/// Parse an IP address from a `for=` or `X-Forwarded-For` token, stripping optional quotes,
261/// IPv6 brackets (`"[2001:db8::1]:4711"`), and IPv4 port (`"192.0.2.1:8080"`).
262fn parse_forwarded_ip(raw: &str) -> Option<IpAddr> {
263    let s = raw.trim().trim_matches('"');
264    if s.is_empty() || s.eq_ignore_ascii_case("unknown") || s.starts_with('_') {
265        return None;
266    }
267    if let Ok(ip) = s.parse::<IpAddr>() {
268        return Some(ip);
269    }
270    if let Some(rest) = s.strip_prefix('[') {
271        let end = rest.find(']')?;
272        return rest[..end].parse::<IpAddr>().ok();
273    }
274    if let Some((host, _port)) = s.rsplit_once(':') {
275        if let Ok(v4) = host.parse::<Ipv4Addr>() {
276            return Some(IpAddr::V4(v4));
277        }
278    }
279    None
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn untrusted_peer_ignores_spoofed_forwarding_headers() {
288        let cfg = TrustedProxyConfig::parse_list("10.0.0.0/8");
289        let peer: IpAddr = "203.0.113.5".parse().unwrap();
290        let hdrs = vec![
291            (
292                "forwarded".into(),
293                "for=198.51.100.7;proto=https;host=evil.test".into(),
294            ),
295            ("x-forwarded-for".into(), "198.51.100.7".into()),
296            ("x-forwarded-proto".into(), "https".into()),
297        ];
298        let res = resolve_client(peer, &hdrs, &cfg);
299        assert_eq!(res.ip, peer);
300        assert_eq!(res.proto, None);
301        assert_eq!(res.host, None);
302    }
303
304    #[test]
305    fn trusted_peer_prefers_rfc7239_forwarded_over_xff() {
306        let cfg = TrustedProxyConfig::parse_list("10.0.0.0/8, 127.0.0.1/32");
307        let peer: IpAddr = "10.1.2.3".parse().unwrap();
308        let hdrs = vec![
309            (
310                "forwarded".into(),
311                "for=\"[2001:db8:cafe::17]:4711\";proto=https;host=git.example.com".into(),
312            ),
313            ("x-forwarded-for".into(), "192.0.2.9".into()),
314            ("x-forwarded-proto".into(), "http".into()),
315        ];
316        let res = resolve_client(peer, &hdrs, &cfg);
317        assert_eq!(res.ip, "2001:db8:cafe::17".parse::<IpAddr>().unwrap());
318        assert_eq!(res.proto.as_deref(), Some("https"));
319        assert_eq!(res.host.as_deref(), Some("git.example.com"));
320    }
321
322    #[test]
323    fn trusted_peer_uses_rightmost_untrusted_xff_hop() {
324        let cfg = TrustedProxyConfig::parse_list("10.0.0.0/8");
325        let peer: IpAddr = "10.0.0.2".parse().unwrap();
326        let hdrs = vec![
327            (
328                "x-forwarded-for".into(),
329                "198.51.100.1, 203.0.113.9, 10.0.0.5".into(),
330            ),
331            ("x-forwarded-proto".into(), "https".into()),
332        ];
333        let res = resolve_client(peer, &hdrs, &cfg);
334        assert_eq!(res.ip, "203.0.113.9".parse::<IpAddr>().unwrap());
335        assert_eq!(res.proto.as_deref(), Some("https"));
336    }
337}