better rate limiting (#1296)

* better rate limiting

* actually reset counter
This commit is contained in:
Aiden McClelland
2022-02-28 13:06:27 -07:00
committed by GitHub
parent b57f12f7ae
commit 86823e063a

View File

@@ -181,7 +181,7 @@ impl Borrow<String> for HashSessionToken {
} }
pub fn auth<M: Metadata>(ctx: RpcContext) -> DynMiddleware<M> { pub fn auth<M: Metadata>(ctx: RpcContext) -> DynMiddleware<M> {
let rate_limiter = Arc::new(Mutex::new(Instant::now())); let rate_limiter = Arc::new(Mutex::new((0_usize, Instant::now())));
Box::new( Box::new(
move |req: &mut Request<Body>, move |req: &mut Request<Body>,
metadata: M| metadata: M|
@@ -205,16 +205,18 @@ pub fn auth<M: Metadata>(ctx: RpcContext) -> DynMiddleware<M> {
Err(e.into()), Err(e.into()),
|_| StatusCode::OK, |_| StatusCode::OK,
)?)); )?));
} else { } else if rpc_req.method.as_str() == "auth.login" {
let mut guard = rate_limiter.lock().await; let mut guard = rate_limiter.lock().await;
if guard.elapsed() < Duration::from_secs(10) { guard.0 += 1;
if guard.1.elapsed() < Duration::from_secs(20) {
if guard.0 >= 3 {
let (res_parts, _) = Response::new(()).into_parts(); let (res_parts, _) = Response::new(()).into_parts();
return Ok(Err(to_response( return Ok(Err(to_response(
&req.headers, &req.headers,
res_parts, res_parts,
Err(Error::new( Err(Error::new(
eyre!( eyre!(
"Please limit login attempts to 1 per 10 seconds." "Please limit login attempts to 3 per 20 seconds."
), ),
crate::ErrorKind::RateLimited, crate::ErrorKind::RateLimited,
) )
@@ -222,7 +224,10 @@ pub fn auth<M: Metadata>(ctx: RpcContext) -> DynMiddleware<M> {
|_| StatusCode::OK, |_| StatusCode::OK,
)?)); )?));
} }
*guard = Instant::now(); } else {
guard.0 = 0;
}
guard.1 = Instant::now();
} }
} }
Ok(Ok(noop3())) Ok(Ok(noop3()))