Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(users): rate limit password sign in and forgot password per email (#15356)

Mani Chandrae45b57645b53
diff --git a/config/config.example.toml b/config/config.example.toml
index b189e5137b..824808a624 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -689,6 +689,9 @@ internal_merchant_id = "juspay000" # Merchant id of the internal merchant that
email_token_expiry_in_secs = 86400 # Number of seconds for which email links (verify, reset password, invite, etc.) stay valid
password_max_attempts = 5 # Wrong passwords in a row before password sign in is locked
password_lock_duration_in_secs = 1800 # Lock time. The failed attempt count also clears after this long without a wrong password
+forgot_password_max_attempts = 5 # Forgot password requests allowed per email within the window
+forgot_password_attempts_window_in_secs = 1800 # Window for forgot password requests. It starts with the first request
+signup_disabled = false # Whether to reject self-serve sign ups (magic link and password)
[oidc.key.k1]
kid = "" # Key ID used to identify the signing key in JWKS and JWT headers (Generate using: openssl rand -hex 16)
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 0985ae9fcb..1a1fd59775 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -249,10 +249,13 @@ two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
password_max_attempts = 5
password_lock_duration_in_secs = 1800
+forgot_password_max_attempts = 5
+forgot_password_attempts_window_in_secs = 1800
totp_issuer_name = "Hyperswitch Integ"
base_url = "https://integ.hyperswitch.io"
force_two_factor_auth = false
force_cookies = false
+signup_disabled = false
accept_password_on_signup_with_merchant_id = false
internal_merchant_id = "juspay000"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index b82ebec00d..802edda708 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -262,10 +262,13 @@ two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
password_max_attempts = 5
password_lock_duration_in_secs = 1800
+forgot_password_max_attempts = 5
+forgot_password_attempts_window_in_secs = 1800
totp_issuer_name = "Hyperswitch Production"
base_url = "https://live.hyperswitch.io"
force_two_factor_auth = true
force_cookies = false
+signup_disabled = true
accept_password_on_signup_with_merchant_id = false
internal_merchant_id = "juspay000"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 7d840700e4..7733b5ace0 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -258,10 +258,13 @@ two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
password_max_attempts = 5
password_lock_duration_in_secs = 1800
+forgot_password_max_attempts = 5
+forgot_password_attempts_window_in_secs = 1800
totp_issuer_name = "Hyperswitch Sandbox"
base_url = "https://app.hyperswitch.io"
force_two_factor_auth = false
force_cookies = false
+signup_disabled = true
accept_password_on_signup_with_merchant_id = false
internal_merchant_id = "juspay000"
diff --git a/config/development.toml b/config/development.toml
index dec412b126..0607e1176c 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -581,10 +581,13 @@ two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
password_max_attempts = 5
password_lock_duration_in_secs = 1800
+forgot_password_max_attempts = 5
+forgot_password_attempts_window_in_secs = 1800
totp_issuer_name = "Hyperswitch Dev"
base_url = "http://localhost:8080"
force_two_factor_auth = false
force_cookies = false
+signup_disabled = false
accept_password_on_signup_with_merchant_id = true
internal_merchant_id = "juspay000"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 47d0d29ab0..80a5858a50 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -126,10 +126,13 @@ two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
password_max_attempts = 5
password_lock_duration_in_secs = 1800
+forgot_password_max_attempts = 5
+forgot_password_attempts_window_in_secs = 1800
totp_issuer_name = "Hyperswitch"
base_url = "http://localhost:9000"
force_two_factor_auth = false
force_cookies = false
+signup_disabled = false
accept_password_on_signup_with_merchant_id = true
internal_merchant_id = "juspay000"
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 96503bf69f..1cf73e55fc 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -1027,6 +1027,9 @@ pub struct UserSettings {
pub email_token_expiry_in_secs: u64,
pub password_max_attempts: u16,
pub password_lock_duration_in_secs: i64,
+ pub forgot_password_max_attempts: u16,
+ pub forgot_password_attempts_window_in_secs: i64,
+ pub signup_disabled: bool,
}
#[derive(Debug, Clone, Default, Deserialize)]
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 34a11cd77a..11e3d5b73d 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -34,6 +34,7 @@ pub const REDIS_RECOVERY_CODE_ATTEMPTS_PREFIX: &str = "RC_ATTEMPTS_";
pub const REDIS_TOTP_ATTEMPTS_TTL_IN_SECS: i64 = 5 * 60; // 5 mins
pub const REDIS_RECOVERY_CODE_ATTEMPTS_TTL_IN_SECS: i64 = 10 * 60; // 10 mins
pub const REDIS_PASSWORD_ATTEMPTS_PREFIX: &str = "PWD_ATTEMPTS_";
+pub const REDIS_FORGOT_PASSWORD_ATTEMPTS_PREFIX: &str = "FORGOT_PWD_ATTEMPTS_";
pub const REDIS_SSO_PREFIX: &str = "SSO_";
pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 2412f4709a..134f5e8830 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -132,6 +132,10 @@ pub enum UserErrors {
InvalidSavedViewName,
#[error("Maximum attempts reached for Password")]
MaxPasswordAttemptsReached,
+ #[error("SignupDisabled")]
+ SignupDisabled,
+ #[error("Maximum attempts reached for Forgot Password")]
+ MaxForgotPasswordAttemptsReached,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -295,9 +299,6 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::ThemeNotFound => {
AER::NotFound(ApiError::new(sub_code, 53, self.get_error_message(), None))
}
- Self::InvalidThemeAssetName => {
- AER::BadRequest(ApiError::new(sub_code, 66, self.get_error_message(), None))
- }
Self::ThemeAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 54, self.get_error_message(), None))
}
@@ -337,9 +338,18 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::InvalidSavedViewName => {
AER::BadRequest(ApiError::new(sub_code, 65, self.get_error_message(), None))
}
+ Self::InvalidThemeAssetName => {
+ AER::BadRequest(ApiError::new(sub_code, 66, self.get_error_message(), None))
+ }
Self::MaxPasswordAttemptsReached => {
AER::TooManyRequests(ApiError::new(sub_code, 67, self.get_error_message(), None))
}
+ Self::SignupDisabled => {
+ AER::BadRequest(ApiError::new(sub_code, 68, self.get_error_message(), None))
+ }
+ Self::MaxForgotPasswordAttemptsReached => {
+ AER::TooManyRequests(ApiError::new(sub_code, 69, self.get_error_message(), None))
+ }
}
}
}
@@ -435,6 +445,10 @@ impl UserErrors {
"Account locked after too many failed sign in attempts. Please try again later"
.to_string()
}
+ Self::SignupDisabled => "Sign up is disabled".to_string(),
+ Self::MaxForgotPasswordAttemptsReached => {
+ "Too many password reset requests. Please try again later".to_string()
+ }
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 6ace815e0f..1c0ca7367f 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -235,6 +235,10 @@ pub async fn signup_token_only_flow(
state: SessionState,
request: user_api::SignUpRequest,
) -> UserResponse<user_api::TokenResponse> {
+ if state.conf.user.signup_disabled {
+ return Err(report!(UserErrors::SignupDisabled));
+ }
+
let user_email = domain::UserEmail::from_pii_email(request.email.clone())?;
utils::user::validate_email_domain_auth_type_using_db(
&state,
@@ -288,31 +292,42 @@ pub async fn signin_token_only_flow(
)
.await?;
- let user_from_db: domain::UserFromStorage = state
- .global_store
- .find_active_user_by_user_email(&user_email)
- .await
- .to_not_found_response(UserErrors::InvalidCredentials)?
- .into();
-
- let user_id = user_from_db.get_user_id();
let max_attempts = i64::from(state.conf.user.password_max_attempts);
- let attempts = utils::user::password::get_password_attempts_from_redis(&state, user_id).await?;
+ let attempts =
+ utils::user::password::get_signin_attempts_from_redis(&state, &user_email).await?;
if attempts >= max_attempts {
return Err(UserErrors::MaxPasswordAttemptsReached.into());
}
- if !user_from_db.compare_password(&request.password)? {
+ let user_from_db = state
+ .global_store
+ .find_active_user_by_user_email(&user_email)
+ .await
+ .map(|user| Some(domain::UserFromStorage::from(user)))
+ .or_else(|error| {
+ if error.current_context().is_db_not_found() {
+ Ok(None)
+ } else {
+ Err(error.change_context(UserErrors::InternalServerError))
+ }
+ })?;
+
+ let are_creds_correct = match &user_from_db {
+ Some(user) => user.compare_password(&request.password)?,
+ None => false,
+ };
+
+ let Some(user_from_db) = user_from_db.filter(|_| are_creds_correct) else {
let attempts =
- utils::user::password::increment_password_attempts_in_redis(&state, user_id).await?;
+ utils::user::password::increment_signin_attempts_in_redis(&state, &user_email).await?;
if attempts >= max_attempts {
return Err(UserErrors::MaxPasswordAttemptsReached.into());
}
return Err(UserErrors::InvalidCredentials.into());
- }
+ };
- let _ = utils::user::password::delete_password_attempts_from_redis(&state, user_id)
+ let _ = utils::user::password::delete_signin_attempts_from_redis(&state, &user_email)
.await
.inspect_err(|error| logger::error!(?error));
@@ -387,8 +402,13 @@ pub async fn connect_account(
.err()
.unwrap_or(false)
{
- if matches!(env::which(), env::Env::Production) {
- return Err(report!(UserErrors::InvalidCredentials));
+ if state.conf.user.signup_disabled {
+ return Ok(ApplicationResponse::Json(
+ user_api::ConnectAccountResponse {
+ is_email_sent: true,
+ user_id: String::new(),
+ },
+ ));
}
let new_user = domain::NewUser::try_from(request)?;
@@ -519,6 +539,7 @@ pub async fn change_password(
let new_password_hash =
utils::user::password::generate_password_hash(new_password.get_secret())?;
+ let user_email = domain::UserEmail::from_pii_email(user.get_email())?;
let _ = state
.global_store
@@ -535,6 +556,9 @@ pub async fn change_password(
let _ = auth::blacklist::insert_user_in_blacklist(&state, user.get_user_id())
.await
.map_err(|error| logger::error!(?error));
+ let _ = utils::user::password::delete_signin_attempts_from_redis(&state, &user_email)
+ .await
+ .map_err(|error| logger::error!(?error));
#[cfg(not(feature = "email"))]
{
@@ -569,18 +593,25 @@ pub async fn forgot_password(
)
.await?;
- let user_from_db = state
+ let attempts =
+ utils::user::password::increment_forgot_password_attempts_in_redis(&state, &user_email)
+ .await?;
+ fp_utils::when(
+ attempts > i64::from(state.conf.user.forgot_password_max_attempts),
+ || Err(UserErrors::MaxForgotPasswordAttemptsReached),
+ )?;
+
+ let user_from_db = match state
.global_store
.find_active_user_by_user_email(&user_email)
.await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::UserNotFound)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })
- .map(domain::UserFromStorage::from)?;
+ {
+ Ok(user) => domain::UserFromStorage::from(user),
+ Err(error) if error.current_context().is_db_not_found() => {
+ return Ok(ApplicationResponse::StatusOk);
+ }
+ Err(error) => return Err(error.change_context(UserErrors::InternalServerError)),
+ };
let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
@@ -627,6 +658,7 @@ pub async fn rotate_password(
if user.compare_password(&request.password)? {
return Err(UserErrors::ChangePasswordError.into());
}
+ let user_email = domain::UserEmail::from_pii_email(user.get_email())?;
let user = state
.global_store
@@ -642,6 +674,9 @@ pub async fn rotate_password(
let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id)
.await
.map_err(|error| logger::error!(?error));
+ let _ = utils::user::password::delete_signin_attempts_from_redis(&state, &user_email)
+ .await
+ .map_err(|error| logger::error!(?error));
auth::cookies::remove_cookie_response()
}
@@ -701,6 +736,10 @@ pub async fn reset_password_token_only_flow(
let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id)
.await
.map_err(|error| logger::error!(?error));
+ let _ =
+ utils::user::password::delete_signin_attempts_from_redis(&state, &email_token.get_email()?)
+ .await
+ .map_err(|error| logger::error!(?error));
auth::cookies::remove_cookie_response()
}
@@ -2267,21 +2306,18 @@ pub async fn send_verification_mail(
)
.await?;
- let user = state
+ let user = match state
.global_store
.find_active_user_by_user_email(&user_email)
.await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::UserNotFound)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?;
-
- if user.is_verified {
- return Err(UserErrors::UserAlreadyVerified.into());
- }
+ {
+ Ok(user) if user.is_verified => return Ok(ApplicationResponse::StatusOk),
+ Ok(user) => user,
+ Err(error) if error.current_context().is_db_not_found() => {
+ return Ok(ApplicationResponse::StatusOk);
+ }
+ Err(error) => return Err(error.change_context(UserErrors::InternalServerError)),
+ };
let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
diff --git a/crates/router/src/utils/user/password.rs b/crates/router/src/utils/user/password.rs
index 25bf4a3b89..8a006e5f62 100644
--- a/crates/router/src/utils/user/password.rs
+++ b/crates/router/src/utils/user/password.rs
@@ -5,15 +5,20 @@ use argon2::{
},
Argon2,
};
-use common_utils::errors::CustomResult;
+use common_utils::{
+ crypto::{self, GenerateDigest},
+ errors::CustomResult,
+};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use rand::{seq::SliceRandom, Rng};
+use redis_interface::RedisKey;
use crate::{
consts,
core::errors::{UserErrors, UserResult},
routes::SessionState,
+ types::domain,
};
pub fn generate_password_hash(
@@ -136,32 +141,39 @@ fn get_temp_password_inner() -> String {
)
}
-fn get_password_attempts_key(user_id: &str) -> String {
- format!(
- "{}{}",
- consts::user::REDIS_PASSWORD_ATTEMPTS_PREFIX,
- user_id
- )
+fn get_email_key(prefix: &str, email: &domain::UserEmail) -> UserResult<RedisKey> {
+ let email_hash = crypto::Sha256
+ .generate_digest(email.clone().get_secret().expose().as_bytes())
+ .change_context(UserErrors::InternalServerError)?;
+ Ok(format!("{prefix}{}", hex::encode(email_hash)).into())
+}
+
+fn get_signin_attempts_key(email: &domain::UserEmail) -> UserResult<RedisKey> {
+ get_email_key(consts::user::REDIS_PASSWORD_ATTEMPTS_PREFIX, email)
+}
+
+fn get_forgot_password_attempts_key(email: &domain::UserEmail) -> UserResult<RedisKey> {
+ get_email_key(consts::user::REDIS_FORGOT_PASSWORD_ATTEMPTS_PREFIX, email)
}
-pub async fn get_password_attempts_from_redis(
+pub async fn get_signin_attempts_from_redis(
state: &SessionState,
- user_id: &str,
+ email: &domain::UserEmail,
) -> UserResult<i64> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
- .get_key::<Option<i64>>(&get_password_attempts_key(user_id).into())
+ .get_key::<Option<i64>>(&get_signin_attempts_key(email)?)
.await
.change_context(UserErrors::InternalServerError)
.map(|v| v.unwrap_or(0))
}
-pub async fn increment_password_attempts_in_redis(
+pub async fn increment_signin_attempts_in_redis(
state: &SessionState,
- user_id: &str,
+ email: &domain::UserEmail,
) -> UserResult<i64> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
- let key = get_password_attempts_key(user_id).into();
+ let key = get_signin_attempts_key(email)?;
let lock_duration_in_secs = state.conf.user.password_lock_duration_in_secs;
let attempts = redis_conn
@@ -176,18 +188,32 @@ pub async fn increment_password_attempts_in_redis(
Ok(attempts)
}
-pub async fn delete_password_attempts_from_redis(
+pub async fn delete_signin_attempts_from_redis(
state: &SessionState,
- user_id: &str,
+ email: &domain::UserEmail,
) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
redis_conn
- .delete_key(&get_password_attempts_key(user_id).into())
+ .delete_key(&get_signin_attempts_key(email)?)
.await
.change_context(UserErrors::InternalServerError)
.map(|_| ())
}
+pub async fn increment_forgot_password_attempts_in_redis(
+ state: &SessionState,
+ email: &domain::UserEmail,
+) -> UserResult<i64> {
+ let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
+ redis_conn
+ .increment_key_with_expiry(
+ &get_forgot_password_attempts_key(email)?,
+ state.conf.user.forgot_password_attempts_window_in_secs,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+
#[cfg(all(test, feature = "deja"))]
mod deja_tests {
use super::UserErrors;