Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

forwarding patch: add support for transports without peer ips (uds) #455

Merged
merged 1 commit into from
Dec 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions forwarding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub use forwarded::Forwarded;
mod parse_utils;

use std::{fmt::Debug, net::IpAddr, ops::Deref};
use trillium::{async_trait, conn_unwrap, Conn, Handler};
use trillium::{async_trait, Conn, Handler, Status};

#[derive(Debug)]
#[non_exhaustive]
Expand Down Expand Up @@ -67,12 +67,12 @@ impl Deref for TrustFn {
}

impl TrustProxy {
fn is_trusted(&self, ip: &IpAddr) -> bool {
match self {
TrustProxy::Always => true,
TrustProxy::Never => false,
TrustProxy::Cidr(cidrs) => cidrs.iter().any(|c| c.contains(ip)),
TrustProxy::Function(trust_predicate) => trust_predicate(ip),
fn is_trusted(&self, ip: Option<IpAddr>) -> bool {
match (self, ip) {
(TrustProxy::Always, _) => true,
(TrustProxy::Cidr(cidrs), Some(ip)) => cidrs.iter().any(|c| c.contains(&ip)),
(TrustProxy::Function(trust_predicate), Some(ip)) => trust_predicate(&ip),
_ => false,
}
}
}
Expand Down Expand Up @@ -150,13 +150,21 @@ impl Default for TrustProxy {
#[async_trait]
impl Handler for Forwarding {
async fn run(&self, mut conn: Conn) -> Conn {
let ip = conn_unwrap!(conn.inner().peer_ip(), conn);
if !self.0.is_trusted(&ip) {
if !self.0.is_trusted(conn.inner().peer_ip()) {
return conn;
}

let forwarded =
conn_unwrap!(Forwarded::from_headers(conn.headers()).ok().flatten(), conn).into_owned();
let forwarded = match Forwarded::from_headers(conn.headers()) {
Ok(Some(forwarded)) => forwarded.into_owned(),
Err(error) => {
log::error!("{error}");
return conn
.halt()
.with_state(error)
.with_status(Status::BadRequest);
}
Ok(None) => return conn,
};

log::debug!("received trusted forwarded {:?}", &forwarded);

Expand Down
7 changes: 7 additions & 0 deletions forwarding/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ fn test_always() {
"true Some(192.0.2.60) None"
);

assert_ok!(
get("/")
.with_request_header("forwarded", "for=192.0.2.60;proto=https;by=203.0.113.43")
.on(&app),
"true Some(192.0.2.60) None"
);

assert_ok!(
get("/")
.with_request_header("x-forwarded-for", "192.0.2.60")
Expand Down
Loading