Skip to content

Commit ba2a545

Browse files
committed
Add the ability to blacklist IPs
We're seeing some suspicious traffic that we think is the causing enough load to be the source of our overall performance problems.
1 parent 681f9a3 commit ba2a545

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/middleware/blacklist_ips.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//! Middleware that blocks requests from a list of given IPs
2+
3+
use super::prelude::*;
4+
5+
use std::io::Cursor;
6+
use std::collections::HashMap;
7+
use std::net::IpAddr;
8+
9+
// Can't derive debug because of Handler.
10+
#[allow(missing_debug_implementations)]
11+
#[derive(Default)]
12+
pub struct BlockIps {
13+
ips: Vec<IpAddr>,
14+
handler: Option<Box<Handler>>,
15+
}
16+
17+
impl BlockIps {
18+
pub fn new(ips: Vec<IpAddr>) -> Self {
19+
Self { ips, handler: None }
20+
}
21+
}
22+
23+
impl AroundMiddleware for BlockIps {
24+
fn with_handler(&mut self, handler: Box<Handler>) {
25+
self.handler = Some(handler);
26+
}
27+
}
28+
29+
impl Handler for BlockIps {
30+
fn call(&self, req: &mut Request) -> Result<Response, Box<Error + Send>> {
31+
if self.ips.contains(&req.remote_addr().ip()) {
32+
let body = format!(
33+
"We are unable to process your request at this time. \
34+
Please open an issue at https://github.com/rust-lang/crates.io \
35+
and provide the request id {}",
36+
req.headers().find("X-Request-Id").unwrap()[0]
37+
);
38+
let mut headers = HashMap::new();
39+
headers.insert("Content-Length".to_string(), vec![body.len().to_string()]);
40+
Ok(Response {
41+
status: (403, "Forbidden"),
42+
headers,
43+
body: Box::new(Cursor::new(body.into_bytes())),
44+
})
45+
} else {
46+
self.handler.as_ref().unwrap().call(req)
47+
}
48+
}
49+
}

src/middleware/mod.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ pub use self::security_headers::SecurityHeaders;
1313
pub use self::static_or_continue::StaticOrContinue;
1414

1515
pub mod app;
16+
mod blacklist_ips;
1617
pub mod current_user;
1718
mod debug;
1819
mod ember_index_rewrite;
@@ -79,5 +80,13 @@ pub fn build_middleware(app: Arc<App>, endpoints: R404) -> MiddlewareBuilder {
7980

8081
m.around(Head::default());
8182

83+
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();
88+
m.around(blacklist_ips::BlockIps::new(ips));
89+
}
90+
8291
m
8392
}

0 commit comments

Comments
 (0)