mirror of
https://github.com/icewind1991/warp-real-ip.git
synced 2026-06-04 03:04:06 +02:00
Allow specifying IP networks for permitted proxies in place of IP addresses.
This commit is contained in:
parent
75a2f210c9
commit
c6af4e7ae9
4 changed files with 45 additions and 5 deletions
33
src/lib.rs
33
src/lib.rs
|
|
@ -1,11 +1,40 @@
|
|||
use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};
|
||||
use rfc7239::{parse, Forwarded, NodeIdentifier, NodeName};
|
||||
use std::convert::Infallible;
|
||||
use std::iter::once;
|
||||
use std::iter::{once, FromIterator, IntoIterator};
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::str::FromStr;
|
||||
use warp::filters::addr::remote;
|
||||
use warp::Filter;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct IpNetworks {
|
||||
networks: Vec<IpNetwork>,
|
||||
}
|
||||
|
||||
impl IpNetworks {
|
||||
pub fn contains(&self, addr: &IpAddr) -> bool {
|
||||
self.networks.iter().any(|&network| network.contains(*addr))
|
||||
}
|
||||
|
||||
pub fn from_ipaddr_iter<'a, T: Iterator<Item = &'a IpAddr>>(addrs: T) -> Self {
|
||||
Self::from_iter(addrs.map(|&addr| -> IpNetwork {
|
||||
match addr {
|
||||
IpAddr::V4(addr) => Ipv4Network::from(addr).into(),
|
||||
IpAddr::V6(addr) => Ipv6Network::from(addr).into(),
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<IpNetwork> for IpNetworks {
|
||||
fn from_iter<T: IntoIterator<Item = IpNetwork>>(addrs: T) -> Self {
|
||||
IpNetworks {
|
||||
networks: Vec::<IpNetwork>::from_iter(addrs),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a `Filter` that provides the "real ip" of the connected client.
|
||||
///
|
||||
/// This uses the "x-forwarded-for" or "x-real-ip" headers set by reverse proxies.
|
||||
|
|
@ -27,7 +56,7 @@ use warp::Filter;
|
|||
/// .map(|addr: Option<IpAddr>| format!("Hello {}", addr.unwrap()));
|
||||
/// ```
|
||||
pub fn real_ip(
|
||||
trusted_proxies: Vec<IpAddr>,
|
||||
trusted_proxies: IpNetworks,
|
||||
) -> impl Filter<Extract = (Option<IpAddr>,), Error = Infallible> + Clone {
|
||||
remote().and(get_forwarded_for()).map(
|
||||
move |addr: Option<SocketAddr>, forwarded_for: Vec<IpAddr>| {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue