From 86823e063ab7115b69d9b19cca748060fd4e8cf0 Mon Sep 17 00:00:00 2001 From: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com> Date: Mon, 28 Feb 2022 13:06:27 -0700 Subject: [PATCH] better rate limiting (#1296) * better rate limiting * actually reset counter --- backend/src/middleware/auth.rs | 37 +++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/backend/src/middleware/auth.rs b/backend/src/middleware/auth.rs index c7a9b118a..4158f8e7f 100644 --- a/backend/src/middleware/auth.rs +++ b/backend/src/middleware/auth.rs @@ -181,7 +181,7 @@ impl Borrow for HashSessionToken { } pub fn auth(ctx: RpcContext) -> DynMiddleware { - let rate_limiter = Arc::new(Mutex::new(Instant::now())); + let rate_limiter = Arc::new(Mutex::new((0_usize, Instant::now()))); Box::new( move |req: &mut Request, metadata: M| @@ -205,24 +205,29 @@ pub fn auth(ctx: RpcContext) -> DynMiddleware { Err(e.into()), |_| StatusCode::OK, )?)); - } else { + } else if rpc_req.method.as_str() == "auth.login" { let mut guard = rate_limiter.lock().await; - if guard.elapsed() < Duration::from_secs(10) { - let (res_parts, _) = Response::new(()).into_parts(); - return Ok(Err(to_response( - &req.headers, - res_parts, - Err(Error::new( - eyre!( - "Please limit login attempts to 1 per 10 seconds." + guard.0 += 1; + if guard.1.elapsed() < Duration::from_secs(20) { + if guard.0 >= 3 { + let (res_parts, _) = Response::new(()).into_parts(); + return Ok(Err(to_response( + &req.headers, + res_parts, + Err(Error::new( + eyre!( + "Please limit login attempts to 3 per 20 seconds." ), - crate::ErrorKind::RateLimited, - ) - .into()), - |_| StatusCode::OK, - )?)); + crate::ErrorKind::RateLimited, + ) + .into()), + |_| StatusCode::OK, + )?)); + } + } else { + guard.0 = 0; } - *guard = Instant::now(); + guard.1 = Instant::now(); } } Ok(Ok(noop3()))