From eeef9cc91694357304d52aa9828a2b0c25225a5b Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 6 Sep 2021 06:56:36 -0400 Subject: [PATCH] fixup IP address handling --- src/http_server/web_utils/ip_address.rs | 26 ++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/http_server/web_utils/ip_address.rs b/src/http_server/web_utils/ip_address.rs index 62f1d3580b..c1b097410e 100644 --- a/src/http_server/web_utils/ip_address.rs +++ b/src/http_server/web_utils/ip_address.rs @@ -69,8 +69,32 @@ fn get_ip_from_header(headers: &HeaderMap, header_name: &str) -> Option if let Ok(header_name) = HeaderName::from_str(header_name) { headers.get(&header_name) .and_then(|value| value.to_str().ok()) - .map(|v| v.to_string()) + .and_then(|value| first_ip_from_list(value)) } else { None } } + +// NB: GKE packs in multiple IP addresses into the header: +// Example of header: x-forwarded-for: Some("136.55.189.34, 34.117.9.171") +fn first_ip_from_list(ip_list: &str) -> Option { + ip_list.split(",") + .into_iter() + .map(|ip| ip.trim()) + .find(|ip| !ip.is_empty()) + .map(|ip| ip.to_string()) +} + +#[cfg(test)] +mod tests { + use crate::http_server::web_utils::ip_address::first_ip_from_list; + + #[test] + fn test_first_ip() { + assert_eq!(first_ip_from_list("1.2.3.4"), Some("1.2.3.4".to_string())); + assert_eq!(first_ip_from_list("1.2.3.4, 34.117.9.171"), Some("1.2.3.4".to_string())); + assert_eq!(first_ip_from_list(", 1.2.3.4"), Some("1.2.3.4".to_string())); + assert_eq!(first_ip_from_list("1.2.3.4, "), Some("1.2.3.4".to_string())); + assert_eq!(first_ip_from_list(""), None); + } +} \ No newline at end of file