Skip to content

Commit

Permalink
real_ip: Add debug logging (#8847)
Browse files Browse the repository at this point in the history
  • Loading branch information
Turbo87 authored Jun 12, 2024
1 parent 665d163 commit 430a09f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/middleware/real_ip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down
9 changes: 8 additions & 1 deletion src/real_ip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ fn is_cloud_front_ip(ip: &IpAddr) -> bool {

pub fn process_xff_headers(headers: &HeaderMap) -> Option<IpAddr> {
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 {
Expand All @@ -55,6 +58,8 @@ pub fn process_xff_headers(headers: &HeaderMap) -> Option<IpAddr> {
// 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())
Expand All @@ -69,6 +74,8 @@ pub fn process_xff_headers(headers: &HeaderMap) -> Option<IpAddr> {
// 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())
Expand Down

0 comments on commit 430a09f

Please sign in to comment.