use crate::{AppError, Result};
use axum::http::HeaderMap;
use serde::{Deserialize, Serialize};
use std::net::{IpAddr, SocketAddr};
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum ClientIpStrategy {
#[default]
Direct,
Forwarded,
XForwardedFor,
XRealIp,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct ClientIpSettings {
pub strategy: ClientIpStrategy,
pub trusted_proxies: Vec<String>,
pub require_proxy: bool,
}
impl ClientIpSettings {
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;
}
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,
}
}
#[derive(Clone, Debug)]
pub struct ClientIpResolver {
settings: ClientIpSettings,
networks: Vec<Network>,
}
impl ClientIpResolver {
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))
}
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
}