Behind a proxy, set X-Real-Ip and use that in the log files

This commit is contained in:
Mike Dilger 2024-02-21 09:04:22 +13:00
parent a09aa5a002
commit f98e9a0832
2 changed files with 17 additions and 3 deletions

View File

@ -23,7 +23,7 @@ server {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-Ip $remote_addr;
proxy_read_timeout 1d;
proxy_send_timeout 1d;
}

View File

@ -30,7 +30,7 @@ use std::error::Error as StdError;
use std::fs::OpenOptions;
use std::future::Future;
use std::io::Read;
use std::net::SocketAddr;
use std::net::{IpAddr, SocketAddr};
use std::pin::Pin;
use std::sync::atomic::Ordering;
use std::task::{Context, Poll};
@ -224,7 +224,21 @@ impl Service<Request<Body>> for HttpService {
// This is called for each HTTP request made by the client
// NOTE: it is not called for each websocket message once upgraded.
fn call(&mut self, req: Request<Body>) -> Self::Future {
let peer = self.peer;
let mut peer = self.peer;
// If chorus is behind a proxy that sets an "X-Real-Ip" header, we use
// that ip address instead (otherwise their log file will just say "127.0.0.1"
// for every peer)
if peer.ip().is_loopback() {
if let Some(rip) = req.headers().get("x-real-ip") {
if let Ok(ripstr) = rip.to_str() {
if let Ok(ipaddr) = ripstr.parse::<IpAddr>() {
peer.set_ip(ipaddr);
}
}
}
}
Box::pin(async move { handle_http_request(peer, req).await })
}
}