simplify functions

This commit is contained in:
2022-04-03 18:10:33 +02:00
parent 627138544f
commit fef8ca84f4
2 changed files with 26 additions and 20 deletions

@ -18,19 +18,23 @@ pub fn match_ip(pattern: &str, ip: &str) -> bool {
/// Get the remote IP address
pub fn get_remote_ip(req: &HttpRequest, proxy_ip: Option<&str>) -> String {
let mut ip = req.peer_addr().unwrap().ip().to_string();
pub fn get_remote_ip(req: &HttpRequest, proxy_ip: Option<&str>) -> IpAddr {
let mut ip = req.peer_addr().unwrap().ip();
// We check if the request comes from a trusted reverse proxy
if let Some(proxy) = proxy_ip.as_ref() {
if match_ip(proxy, &ip) {
if match_ip(proxy, &ip.to_string()) {
if let Some(header) = req.headers().get("X-Forwarded-For") {
let header = header.to_str().unwrap();
if let Some((upstream_ip, _)) = header.split_once(',') {
ip = upstream_ip.to_string();
let remote_ip = if let Some((upstream_ip, _)) = header.split_once(',') {
upstream_ip
} else {
ip = header.to_string();
header
};
if let Some(upstream_ip) = parse_ip(remote_ip) {
ip = upstream_ip;
}
}
}
@ -74,7 +78,7 @@ mod test {
let req = TestRequest::default()
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
.to_http_request();
assert_eq!(get_remote_ip(&req, None), "192.168.1.1");
assert_eq!(get_remote_ip(&req, None), "192.168.1.1".parse::<IpAddr>().unwrap());
}
#[test]
@ -83,7 +87,7 @@ mod test {
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
.insert_header(("X-Forwarded-For", "1.1.1.1"))
.to_http_request();
assert_eq!(get_remote_ip(&req, Some("192.168.1.1")), "1.1.1.1");
assert_eq!(get_remote_ip(&req, Some("192.168.1.1")), "1.1.1.1".parse::<IpAddr>().unwrap());
}
#[test]
@ -92,7 +96,16 @@ mod test {
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
.insert_header(("X-Forwarded-For", "1.1.1.1, 1.2.2.2"))
.to_http_request();
assert_eq!(get_remote_ip(&req, Some("192.168.1.1")), "1.1.1.1");
assert_eq!(get_remote_ip(&req, Some("192.168.1.1")), "1.1.1.1".parse::<IpAddr>().unwrap());
}
#[test]
fn test_get_remote_ip_from_proxy_ipv6() {
let req = TestRequest::default()
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
.insert_header(("X-Forwarded-For", "10::1, 1.2.2.2"))
.to_http_request();
assert_eq!(get_remote_ip(&req, Some("192.168.1.1")), "10::".parse::<IpAddr>().unwrap());
}
#[test]
@ -101,7 +114,7 @@ mod test {
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
.insert_header(("X-Forwarded-For", "1.1.1.1, 1.2.2.2"))
.to_http_request();
assert_eq!(get_remote_ip(&req, None), "192.168.1.1");
assert_eq!(get_remote_ip(&req, None), "192.168.1.1".parse::<IpAddr>().unwrap());
}
#[test]
@ -110,7 +123,7 @@ mod test {
.peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap())
.insert_header(("X-Forwarded-For", "1.1.1.1, 1.2.2.2"))
.to_http_request();
assert_eq!(get_remote_ip(&req, Some("192.168.1.2")), "192.168.1.1");
assert_eq!(get_remote_ip(&req, Some("192.168.1.2")), "192.168.1.1".parse::<IpAddr>().unwrap());
}
#[test]