webserver_base/
ip.rs

1use std::{collections::HashMap, net::SocketAddr};
2
3use axum::http::HeaderMap;
4use tracing::{error, info, instrument};
5
6/// Determine the client's actual IP address (not the IP address of any Proxies).
7#[instrument(skip_all)]
8pub fn resolve_true_client_ip_address(socket_addr: SocketAddr, header_map: HeaderMap) -> String {
9    // prioritized list of HTTP headers that may contain the client's true IP address
10    // (top-most entry is the most trusted)
11    let prioritized_headers: Vec<&str> = vec![
12        // Cloudflare
13        "True-Client-IP",
14        "CF-Connecting-IP",
15        // standard
16        "X-Forwarded-For",
17        "X-Real-IP",
18        "Forwarded",
19        // backup (Axum's 'SocketAddr' IP; definitely a proxy)
20        "socket_addr",
21    ];
22
23    // get the value of each prioritized header (if it exists)
24    let prioritized_headers_values: HashMap<&str, Option<String>> = prioritized_headers.iter().map(|prioritized_header| {
25            if *prioritized_header == "socket_addr" {
26                // this is a backup in the case we fail to get 'true' IP address
27                // (usually a Proxy IP)
28                return (*prioritized_header, Some(socket_addr.ip().to_string()));
29            }
30
31            let header_value: Option<String> = match header_map.get(*prioritized_header) {
32                // prioritized header exists in the HeaderMap
33                Some(header_value) => {
34                    match header_value.to_str() {
35                        // successfully parsed HTTP header value
36                        Ok(header_value) => {
37                            if *prioritized_header == "X-Forwarded-For" {
38                                info!("full HTTP 'X-Forwarded-For' header IP list: {header_value}");
39
40                                // 'X-Forwarded-For' header may contain multiple IP addresses
41                                let parts: Vec<&str> = header_value.split(',').collect();
42
43                                // if there are multiple entries in this list, the left-most entry is the
44                                // client's actual IP address (all other entries are Network Proxies)
45                                let x_forwarded_for_client_ip: Option<&&str> = parts.first();
46                                if let Some(x_forwarded_for_client_ip) = x_forwarded_for_client_ip {
47                                    let x_forwarded_for: String = (*x_forwarded_for_client_ip).to_string();
48                                    Some(x_forwarded_for)
49                                } else {
50                                    // zero IP addresses found in 'X-Forwarded-For' header
51                                    None
52                                }
53                            } else {
54                                // all other headers are single IP addresses
55                                Some(header_value.to_string())
56                            }
57                        }
58                        // failed to parse HTTP header value
59                        Err(to_str_error) => {
60                            error!("failed to parse HTTP '{prioritized_header}' header value: {to_str_error}");
61                            None
62                        }
63                    }
64                }
65                // prioritized header does not exist in the HeaderMap
66                None => {
67                    None
68                },
69            };
70            (*prioritized_header, header_value)
71        }).collect();
72    info!(
73        "Client IP headers: {:?}",
74        prioritized_headers_values.clone()
75    );
76
77    // choose the first prioritized header that exists
78    for prioritized_header in prioritized_headers {
79        if let Some(Some(header_value)) = prioritized_headers_values.get(prioritized_header) {
80            info!("chose HTTP '{prioritized_header}' header for true client IP: '{header_value}'");
81            return header_value.to_string();
82        }
83    }
84
85    // THIS SHOULD NEVER BE HIT because 'socket_addr' always exists
86    error!("failed to find any prioritized HTTP headers for true client IP address");
87    prioritized_headers_values
88        .get("socket_addr")
89        .unwrap()
90        .as_ref()
91        .unwrap()
92        .to_string()
93}