Skip to content

Commit b311ab3

Browse files
committed
Fix IP blacklisting
It turns out `req.remote_addr()` is just always returning localhost with a port. The actual IP we want is in the `X-Forwarded-For` header, which appears to always be the a comma separated list of IPs with spaces, one of which is the one we want. This makes the "is this IP in there" much wonkier (why can't I call `Vec<String>::contains(&str)`?), but this should get us what we want. Heroku will always provide an `X-Forwarded-For` header.
1 parent 70406bd commit b311ab3

File tree

2 files changed

+9
-8
lines changed

2 files changed

+9
-8
lines changed

src/middleware/blacklist_ips.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,17 @@ use super::prelude::*;
44

55
use std::io::Cursor;
66
use std::collections::HashMap;
7-
use std::net::IpAddr;
87

98
// Can't derive debug because of Handler.
109
#[allow(missing_debug_implementations)]
1110
#[derive(Default)]
1211
pub struct BlockIps {
13-
ips: Vec<IpAddr>,
12+
ips: Vec<String>,
1413
handler: Option<Box<Handler>>,
1514
}
1615

1716
impl BlockIps {
18-
pub fn new(ips: Vec<IpAddr>) -> Self {
17+
pub fn new(ips: Vec<String>) -> Self {
1918
Self { ips, handler: None }
2019
}
2120
}
@@ -28,7 +27,12 @@ impl AroundMiddleware for BlockIps {
2827

2928
impl Handler for BlockIps {
3029
fn call(&self, req: &mut Request) -> Result<Response, Box<Error + Send>> {
31-
if self.ips.contains(&req.remote_addr().ip()) {
30+
let has_blacklisted_ip = req.headers()
31+
.find("X-Forwarded-For")
32+
.unwrap()
33+
.iter()
34+
.any(|v| v.split(", ").any(|ip| self.ips.iter().any(|x| x == ip)));
35+
if has_blacklisted_ip {
3236
let body = format!(
3337
"We are unable to process your request at this time. \
3438
Please open an issue at https://github.com/rust-lang/crates.io \

src/middleware/mod.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,7 @@ pub fn build_middleware(app: Arc<App>, endpoints: R404) -> MiddlewareBuilder {
8181
m.around(Head::default());
8282

8383
if let Ok(ip_list) = env::var("BLACKLISTED_IPS") {
84-
let ips = ip_list
85-
.split(',')
86-
.map(|s| s.parse().expect("Could not parse IP address"))
87-
.collect();
84+
let ips = ip_list.split(',').map(String::from).collect();
8885
m.around(blacklist_ips::BlockIps::new(ips));
8986
}
9087

0 commit comments

Comments
 (0)