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): lock password sign in after 5 consecutive failed attempts (#15349)

Kanika Bansal7d0cee2c8250
diff --git a/config/config.example.toml b/config/config.example.toml
index d441628f7d..90077efabd 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -686,6 +686,8 @@ force_cookies = false # Whether to use only cookies for JWT extra
internal_merchant_id = "juspay000" # Merchant id of the internal merchant that internal users are created under
# idle_session_timeout_in_secs = 900 # When set, signs Dashboard users out after this many seconds without a request
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
[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 a9c9136605..42da4c74b6 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -247,6 +247,8 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
+password_max_attempts = 5
+password_lock_duration_in_secs = 1800
totp_issuer_name = "Hyperswitch Integ"
base_url = "https://integ.hyperswitch.io"
force_two_factor_auth = false
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 4b04121dab..4b4a639e62 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -260,6 +260,8 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
+password_max_attempts = 5
+password_lock_duration_in_secs = 1800
totp_issuer_name = "Hyperswitch Production"
base_url = "https://live.hyperswitch.io"
force_two_factor_auth = true
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 717b5a5a10..e17aae1668 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -256,6 +256,8 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
+password_max_attempts = 5
+password_lock_duration_in_secs = 1800
totp_issuer_name = "Hyperswitch Sandbox"
base_url = "https://app.hyperswitch.io"
force_two_factor_auth = false
diff --git a/config/development.toml b/config/development.toml
index 8dd6c4427a..fa06700278 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -579,6 +579,8 @@ sts_role_session_name = ""
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
+password_max_attempts = 5
+password_lock_duration_in_secs = 1800
totp_issuer_name = "Hyperswitch Dev"
base_url = "http://localhost:8080"
force_two_factor_auth = false
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 6f25ea7299..56e130393b 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -124,6 +124,8 @@ master_enc_key = "73ad7bbbbc640c845a150f67d058b279849370cd2c1f3c67c4dd6c869213e1
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
email_token_expiry_in_secs = 86400
+password_max_attempts = 5
+password_lock_duration_in_secs = 1800
totp_issuer_name = "Hyperswitch"
base_url = "http://localhost:9000"
force_two_factor_auth = false
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 8299e9d33a..8f5614e66e 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -1023,6 +1023,8 @@ pub struct UserSettings {
pub idle_session_timeout_in_secs: Option<u32>,
pub internal_merchant_id: common_utils::id_type::MerchantId,
pub email_token_expiry_in_secs: u64,
+ pub password_max_attempts: u16,
+ pub password_lock_duration_in_secs: i64,
}
#[derive(Debug, Clone, Default, Deserialize)]
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index a62b8c8533..34a11cd77a 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -33,6 +33,7 @@ pub const REDIS_TOTP_ATTEMPTS_PREFIX: &str = "TOTP_ATTEMPTS_";
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_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 c14ef8fb5e..2412f4709a 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -130,6 +130,8 @@ pub enum UserErrors {
SavedViewNotFound,
#[error("InvalidSavedViewName")]
InvalidSavedViewName,
+ #[error("Maximum attempts reached for Password")]
+ MaxPasswordAttemptsReached,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -335,6 +337,9 @@ 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::MaxPasswordAttemptsReached => {
+ AER::TooManyRequests(ApiError::new(sub_code, 67, self.get_error_message(), None))
+ }
}
}
}
@@ -426,6 +431,10 @@ impl UserErrors {
Self::InvalidSavedViewName => {
"The saved view name cannot be empty or contain only whitespace".to_string()
}
+ Self::MaxPasswordAttemptsReached => {
+ "Account locked after too many failed sign in attempts. Please try again later"
+ .to_string()
+ }
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 09dd49c628..6abb7ece55 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -292,7 +292,26 @@ pub async fn signin_token_only_flow(
.to_not_found_response(UserErrors::InvalidCredentials)?
.into();
- user_from_db.compare_password(&request.password)?;
+ 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?;
+ if attempts >= max_attempts {
+ return Err(UserErrors::MaxPasswordAttemptsReached.into());
+ }
+
+ if !user_from_db.compare_password(&request.password)? {
+ let attempts =
+ utils::user::password::increment_password_attempts_in_redis(&state, user_id).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)
+ .await
+ .inspect_err(|error| logger::error!(?error));
let next_flow =
domain::NextFlow::from_origin(domain::Origin::SignIn, user_from_db.clone(), &state).await?;
@@ -486,8 +505,9 @@ pub async fn change_password(
.change_context(UserErrors::InternalServerError)?
.into();
- user.compare_password(&request.old_password)
- .change_context(UserErrors::InvalidOldPassword)?;
+ if !user.compare_password(&request.old_password)? {
+ return Err(UserErrors::InvalidOldPassword.into());
+ }
if request.old_password == request.new_password {
return Err(UserErrors::ChangePasswordError.into());
@@ -601,7 +621,7 @@ pub async fn rotate_password(
let password = domain::UserPassword::new(request.password.to_owned())?;
let hash_password = utils::user::password::generate_password_hash(password.get_secret())?;
- if user.compare_password(&request.password).is_ok() {
+ if user.compare_password(&request.password)? {
return Err(UserErrors::ChangePasswordError.into());
}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index acbae53af2..cb17d4daf1 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -1193,15 +1193,10 @@ impl UserFromStorage {
self.0.user_id.as_str()
}
- pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()> {
- if let Some(password) = self.0.password.as_ref() {
- match password::is_correct_password(candidate, password) {
- Ok(true) => Ok(()),
- Ok(false) => Err(UserErrors::InvalidCredentials.into()),
- Err(e) => Err(e),
- }
- } else {
- Err(UserErrors::InvalidCredentials.into())
+ pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<bool> {
+ match self.0.password.as_ref() {
+ Some(password) => password::is_correct_password(candidate, password),
+ None => Ok(false),
}
}
diff --git a/crates/router/src/utils/user/password.rs b/crates/router/src/utils/user/password.rs
index 4e52ef3db3..25bf4a3b89 100644
--- a/crates/router/src/utils/user/password.rs
+++ b/crates/router/src/utils/user/password.rs
@@ -10,7 +10,11 @@ use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use rand::{seq::SliceRandom, Rng};
-use crate::core::errors::UserErrors;
+use crate::{
+ consts,
+ core::errors::{UserErrors, UserResult},
+ routes::SessionState,
+};
pub fn generate_password_hash(
password: Secret<String>,
@@ -132,6 +136,58 @@ fn get_temp_password_inner() -> String {
)
}
+fn get_password_attempts_key(user_id: &str) -> String {
+ format!(
+ "{}{}",
+ consts::user::REDIS_PASSWORD_ATTEMPTS_PREFIX,
+ user_id
+ )
+}
+
+pub async fn get_password_attempts_from_redis(
+ state: &SessionState,
+ user_id: &str,
+) -> 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())
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|v| v.unwrap_or(0))
+}
+
+pub async fn increment_password_attempts_in_redis(
+ state: &SessionState,
+ user_id: &str,
+) -> UserResult<i64> {
+ let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
+ let key = get_password_attempts_key(user_id).into();
+ let lock_duration_in_secs = state.conf.user.password_lock_duration_in_secs;
+
+ let attempts = redis_conn
+ .increment_key_with_expiry(&key, lock_duration_in_secs)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+ redis_conn
+ .set_expiry(&key, lock_duration_in_secs)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(attempts)
+}
+
+pub async fn delete_password_attempts_from_redis(
+ state: &SessionState,
+ user_id: &str,
+) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
+ redis_conn
+ .delete_key(&get_password_attempts_key(user_id).into())
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|_| ())
+}
+
#[cfg(all(test, feature = "deja"))]
mod deja_tests {
use super::UserErrors;