1use crate::{AppError, Result};
2use axum::http::HeaderMap;
3use serde::{Deserialize, Serialize};
4use std::net::{IpAddr, SocketAddr};
5
6#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
8#[serde(rename_all = "kebab-case")]
9pub enum ClientIpStrategy {
10 #[default]
12 Direct,
13 Forwarded,
15 XForwardedFor,
17 XRealIp,
19}
20#[derive(Clone, Debug, Default, Deserialize, Serialize)]
22#[serde(default, deny_unknown_fields)]
23pub struct ClientIpSettings {
24 pub strategy: ClientIpStrategy,
26 pub trusted_proxies: Vec<String>,
28 pub require_proxy: bool,
31}
32impl ClientIpSettings {
33 pub fn validate(&self) -> Result<()> {
36 ClientIpResolver::new(self).map(|_| ())
37 }
38}
39#[derive(Clone, Debug)]
40struct Network {
41 ip: IpAddr,
42 prefix: u32,
43}
44impl Network {
45 fn parse(value: &str) -> Option<Self> {
46 let (ip, prefix) = value.split_once('/')?;
47 let ip: IpAddr = ip.parse().ok()?;
48 let prefix: u32 = prefix.parse().ok()?;
49 if prefix == 0 || prefix > if ip.is_ipv4() { 32 } else { 128 } {
50 return None;
51 }
52 if matches!(ip, IpAddr::V6(v) if v.to_ipv4_mapped().is_some()) {
54 return None;
55 }
56 Some(Self { ip, prefix })
57 }
58 fn contains(&self, ip: IpAddr) -> bool {
59 match (self.ip, canonical(ip)) {
60 (IpAddr::V4(net), IpAddr::V4(ip)) => {
61 u32::from(net) >> (32 - self.prefix) == u32::from(ip) >> (32 - self.prefix)
62 }
63 (IpAddr::V6(net), IpAddr::V6(ip)) => {
64 u128::from(net) >> (128 - self.prefix) == u128::from(ip) >> (128 - self.prefix)
65 }
66 _ => false,
67 }
68 }
69}
70fn canonical(ip: IpAddr) -> IpAddr {
71 match ip {
72 IpAddr::V6(v) => v.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(ip),
73 _ => ip,
74 }
75}
76#[derive(Clone, Debug)]
80pub struct ClientIpResolver {
81 settings: ClientIpSettings,
82 networks: Vec<Network>,
83}
84impl ClientIpResolver {
85 pub fn new(settings: &ClientIpSettings) -> Result<Self> {
87 let invalid = || {
88 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())
89 };
90 if settings.trusted_proxies.len() > 64
91 || (settings.strategy == ClientIpStrategy::Direct
92 && (settings.require_proxy || !settings.trusted_proxies.is_empty()))
93 || (settings.strategy != ClientIpStrategy::Direct
94 && settings.trusted_proxies.is_empty())
95 {
96 return Err(invalid());
97 }
98 let networks = settings
99 .trusted_proxies
100 .iter()
101 .map(|s| Network::parse(s).ok_or_else(invalid))
102 .collect::<Result<Vec<_>>>()?;
103 Ok(Self {
104 settings: settings.clone(),
105 networks,
106 })
107 }
108 fn trusted(&self, ip: IpAddr) -> bool {
109 self.networks.iter().any(|net| net.contains(ip))
110 }
111 pub fn resolve(&self, peer: Option<SocketAddr>, headers: &HeaderMap) -> Result<IpAddr> {
114 let fail = |reason| {
115 tracing::warn!(event = "http.client_ip.unavailable", reason);
116 AppError::ClientIdentityUnavailable
117 };
118 let peer = canonical(peer.ok_or_else(|| fail("missing_peer"))?.ip());
119 if peer.is_unspecified() || peer.is_multicast() {
120 return Err(fail("invalid_peer"));
121 }
122 if self.settings.strategy == ClientIpStrategy::Direct {
123 return Ok(peer);
124 }
125 if !self.trusted(peer) {
126 return if self.settings.require_proxy {
127 Err(fail("untrusted_peer"))
128 } else {
129 Ok(peer)
130 };
131 }
132 let name = match self.settings.strategy {
133 ClientIpStrategy::Forwarded => "forwarded",
134 ClientIpStrategy::XForwardedFor => "x-forwarded-for",
135 ClientIpStrategy::XRealIp => "x-real-ip",
136 ClientIpStrategy::Direct => unreachable!(),
137 };
138 let mut chain = Vec::new();
139 let mut bytes = 0usize;
140 for value in headers.get_all(name) {
141 bytes = bytes.saturating_add(value.len());
142 if bytes > 8192 {
143 return Err(fail("header_too_large"));
144 }
145 let value = value.to_str().map_err(|_| fail("malformed_header"))?;
146 for hop in value.split(',') {
147 if chain.len() == 32 {
148 return Err(fail("too_many_hops"));
149 }
150 let ip = if self.settings.strategy == ClientIpStrategy::Forwarded {
151 forwarded(hop)
152 } else {
153 hop.trim().parse().ok()
154 };
155 let ip = canonical(ip.ok_or_else(|| fail("malformed_header"))?);
156 if ip.is_unspecified() || ip.is_multicast() {
157 return Err(fail("invalid_address"));
158 }
159 chain.push(ip);
160 }
161 }
162 if self.settings.strategy == ClientIpStrategy::XRealIp && chain.len() != 1 {
163 return Err(fail("ambiguous_header"));
164 }
165 for ip in chain.into_iter().rev() {
166 if !self.trusted(ip) {
167 return Ok(ip);
168 }
169 }
170 Err(fail("missing_client_boundary"))
171 }
172}
173fn forwarded(hop: &str) -> Option<IpAddr> {
174 let mut address = None;
175 for pair in hop.split(';') {
176 let (key, value) = pair.trim().split_once('=')?;
177 if !key.eq_ignore_ascii_case("for") {
178 continue;
179 }
180 if address.is_some() {
181 return None;
182 }
183 let value = value.trim();
184 let value = if value.starts_with('"') {
185 value.strip_prefix('"')?.strip_suffix('"')?
186 } else {
187 value
188 };
189 let ip = value
190 .parse()
191 .ok()
192 .or_else(|| value.parse::<SocketAddr>().ok().map(|a| a.ip()))
193 .or_else(|| value.strip_prefix('[')?.strip_suffix(']')?.parse().ok())?;
194 address = Some(ip);
195 }
196 address
197}