always trust X-Forwarded-For

This commit is contained in:
b1ek 2025-02-25 16:55:17 +10:00
parent bbca7bf628
commit 9d4382356d
Signed by: blek
GPG Key ID: A622C22C9BC616B2
1 changed files with 13 additions and 3 deletions

View File

@ -1,4 +1,4 @@
use std::{convert::Infallible, future::Future, net::SocketAddr, pin::Pin};
use std::{convert::Infallible, future::Future, net::{IpAddr, SocketAddr}, pin::Pin};
use hyper::{body::Incoming, header::HeaderValue, server::conn::http1, service::Service as ServiceTrait, Request, Response, StatusCode};
use tokio::net::TcpListener;
@ -13,8 +13,18 @@ impl ServiceTrait<Request<Incoming>> for Service {
type Error = Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn call(&self, _req: Request<Incoming>) -> Self::Future {
if let Some(ip) = self.remote_ip {
fn call(&self, req: Request<Incoming>) -> Self::Future {
let mut remote_ip = self.remote_ip;
if let Some(ip) = req.headers().get("X-Forwarded-For") {
if let Ok(str_ip) = ip.to_str() {
if let Ok(ip) = str_ip.parse::<SocketAddr>() {
remote_ip = Some(ip);
}
}
}
if let Some(ip) = remote_ip {
let mut res = Response::new(ip.ip().to_string());
res.headers_mut().append("Content-Type", HeaderValue::from_static("text/plain"));
Box::pin(async { Ok(res) })