Skip to content

Commit

Permalink
backend/get_login_salt: add rate litmit.
Browse files Browse the repository at this point in the history
  • Loading branch information
ffreddow committed Dec 18, 2024
1 parent 68af5a8 commit 80caf7b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
14 changes: 13 additions & 1 deletion backend/src/rate_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@ pub struct LoginRateLimitKey {
ip: String,
}

#[cfg(test)]
const REQUESTS_PER_SECOND: u32 = 1;

#[cfg(test)]
const REQUESTS_BURST: u32 = 5;

#[cfg(not(test))]
const REQUESTS_PER_SECOND: u32 = 5;

#[cfg(not(test))]
const REQUESTS_BURST: u32 = 25;

// RateLimiter for the login route
pub struct LoginRateLimiter {
rate_limiter: RateLimiter<LoginRateLimitKey, dashmap::DashMap<LoginRateLimitKey, InMemoryState>, QuantaClock, governor::middleware::NoOpMiddleware<governor::clock::QuantaInstant>>,
Expand All @@ -68,7 +80,7 @@ pub struct LoginRateLimiter {
impl LoginRateLimiter {
pub fn new() -> Self {
Self {
rate_limiter: RateLimiter::keyed(Quota::per_second(NonZeroU32::new(1).unwrap()).allow_burst(NonZeroU32::new(5).unwrap())),
rate_limiter: RateLimiter::keyed(Quota::per_second(NonZeroU32::new(REQUESTS_PER_SECOND).unwrap()).allow_burst(NonZeroU32::new(REQUESTS_BURST).unwrap())),
}
}

Expand Down
10 changes: 6 additions & 4 deletions backend/src/routes/auth/get_login_salt.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
use std::sync::Mutex;

use actix_web::{get, web, HttpResponse, Responder};
use actix_web::{get, web, HttpRequest, HttpResponse, Responder};
use db_connector::models::users::User;
use diesel::{prelude::*, result::Error::NotFound};
use lru::LruCache;
use serde::Deserialize;
use utoipa::IntoParams;

use crate::{
error::Error,
utils::{generate_random_bytes, get_connection, web_block_unpacked},
AppState,
error::Error, rate_limit::LoginRateLimiter, utils::{generate_random_bytes, get_connection, web_block_unpacked}, AppState
};

#[derive(Deserialize, IntoParams)]
Expand All @@ -34,10 +32,14 @@ pub async fn get_login_salt(
state: web::Data<AppState>,
query: web::Query<GetSaltQuery>,
cache: web::Data<Mutex<LruCache<String, Vec<u8>>>>,
rate_limiter: web::Data<LoginRateLimiter>,
req: HttpRequest,
) -> actix_web::Result<impl Responder> {
use db_connector::schema::users::dsl::*;

let mail = query.email.to_lowercase();
rate_limiter.check(mail.clone(), &req)?;

let mut conn = get_connection(&state)?;
let salt: Vec<u8> = web_block_unpacked(move || {
match users
Expand Down

0 comments on commit 80caf7b

Please sign in to comment.