diff --git a/src/middleware/real_ip.rs b/src/middleware/real_ip.rs index fcbe4c41eba..1d691eaf3ad 100644 --- a/src/middleware/real_ip.rs +++ b/src/middleware/real_ip.rs @@ -13,7 +13,13 @@ pub async fn middleware( next: Next, ) -> impl IntoResponse { let xff_ip = process_xff_headers(req.headers()); - let real_ip = xff_ip.unwrap_or_else(|| socket_addr.ip()); + let real_ip = xff_ip + .inspect(|ip| debug!(target: "real_ip", "Using X-Forwarded-For header as real IP: {ip}")) + .unwrap_or_else(|| { + let ip = socket_addr.ip(); + debug!(target: "real_ip", "Using socket address as real IP: {ip}"); + ip + }); req.extensions_mut().insert(RealIp(real_ip)); diff --git a/src/real_ip.rs b/src/real_ip.rs index e02aed37a45..e009015aa5a 100644 --- a/src/real_ip.rs +++ b/src/real_ip.rs @@ -40,7 +40,10 @@ fn is_cloud_front_ip(ip: &IpAddr) -> bool { pub fn process_xff_headers(headers: &HeaderMap) -> Option { let mut xff_iter = headers.get_all(X_FORWARDED_FOR).iter(); - let first_header = xff_iter.next()?; + let Some(first_header) = xff_iter.next() else { + debug!(target: "real_ip", "No X-Forwarded-For header found"); + return None; + }; let has_more_headers = xff_iter.next().is_some(); return if has_more_headers { @@ -55,6 +58,8 @@ pub fn process_xff_headers(headers: &HeaderMap) -> Option { // have to care about the trusted proxies, since the request was // apparently sent to Heroku directly. + debug!(target: "real_ip", ?first_header, "Multiple X-Forwarded-For headers found, using the first one due to Heroku bug"); + parse_xff_header(first_header) .into_iter() .filter_map(|r| r.ok()) @@ -69,6 +74,8 @@ pub fn process_xff_headers(headers: &HeaderMap) -> Option { // In this case return the right-most IP address that is not in the list // of IPs from trusted proxies (i.e. CloudFront). + debug!(target: "real_ip", ?first_header, "Single X-Forwarded-For header found"); + parse_xff_header(first_header) .into_iter() .filter_map(|r| r.ok())