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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(users): expire dashboard sessions after inactivity (#14794)
Rohan Malid9d0900f8a4c
diff --git a/config/config.example.toml b/config/config.example.tomlindex ff67d1bb87..c9effbfe0a 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -681,6 +681,7 @@ totp_issuer_name = "Hyperswitch" # Name of the issuer for TOTPbase_url = "" # Base url used for user specific redirects and emailsforce_two_factor_auth = false # Whether to force two factor authentication for all usersforce_cookies = false # Whether to use only cookies for JWT extraction and authentication+# idle_session_timeout_in_secs = 900 # When set, signs Dashboard users out after this many seconds without a request[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/production.toml b/config/deployments/production.tomlindex 4262b69688..b84ccb5b61 100644--- a/config/deployments/production.toml+++ b/config/deployments/production.toml@@ -261,6 +261,7 @@ totp_issuer_name = "Hyperswitch Production"base_url = "https://live.hyperswitch.io"force_two_factor_auth = trueforce_cookies = false+idle_session_timeout_in_secs = 900[frm]enabled = falsediff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 0eafba1374..3825c7e5e7 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -1019,6 +1019,7 @@ pub struct UserSettings {pub base_url: String,pub force_two_factor_auth: bool,pub force_cookies: bool,+ pub idle_session_timeout_in_secs: Option<u32>,}#[derive(Debug, Clone, Default, Deserialize)]@@ -1638,6 +1639,7 @@ impl Settings<SecuredSecret> {self.connectors.validate("connectors")?;self.sage.get_inner().validate()?;self.cors.validate()?;+ self.user.validate()?;self.scheduler.as_ref()diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rsindex 3e2c0dfd11..c0081b2712 100644--- a/crates/router/src/configs/validations.rs+++ b/crates/router/src/configs/validations.rs@@ -2,6 +2,8 @@ use common_utils::ext_traits::ConfigExt;use hyperswitch_masking::PeekInterface;use storage_impl::errors::ApplicationError;+use crate::consts::MIN_IDLE_SESSION_TIMEOUT_IN_SECS;+impl super::settings::Secrets {pub fn validate(&self) -> Result<(), ApplicationError> {use common_utils::fp_utils::when;@@ -26,6 +28,25 @@ impl super::settings::Secrets {}}+impl super::settings::UserSettings {+ pub fn validate(&self) -> Result<(), ApplicationError> {+ use common_utils::fp_utils::when;++ when(+ self.idle_session_timeout_in_secs+ .is_some_and(|idle_timeout_in_secs| {+ idle_timeout_in_secs < MIN_IDLE_SESSION_TIMEOUT_IN_SECS+ }),+ || {+ Err(ApplicationError::InvalidConfigurationValueError(format!(+ "user idle session timeout must be at least \+ {MIN_IDLE_SESSION_TIMEOUT_IN_SECS} seconds when set"+ )))+ },+ )+ }+}+impl super::settings::Locker {pub fn validate(&self) -> Result<(), ApplicationError> {use common_utils::fp_utils::when;diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex d86ac9f19e..1b06ef72ce 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -74,6 +74,9 @@ pub const USER_BLACKLIST_PREFIX: &str = "BU_";pub const ROLE_BLACKLIST_PREFIX: &str = "BR_";+pub const USER_IDLE_SESSION_PREFIX: &str = "IS_";+pub const MIN_IDLE_SESSION_TIMEOUT_IN_SECS: u32 = 60;+#[cfg(feature = "email")]pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 daydiff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rsindex 85fa9ed87e..38cc569a25 100644--- a/crates/router/src/core/user.rs+++ b/crates/router/src/core/user.rs@@ -51,7 +51,7 @@ use crate::{types::{domain, transformers::ForeignInto},utils::{self,- user::{theme as theme_utils, two_factor_auth as tfa_utils},+ user::{end_user_sessions, theme as theme_utils, two_factor_auth as tfa_utils},},};#[cfg(feature = "v1")]@@ -474,11 +474,7 @@ pub async fn signout(state: SessionState,user_from_token: auth::UserIdFromAuth,) -> UserResponse<()> {- tfa_utils::delete_totp_from_redis(&state, &user_from_token.user_id).await?;- tfa_utils::delete_recovery_code_from_redis(&state, &user_from_token.user_id).await?;- tfa_utils::delete_totp_secret_from_redis(&state, &user_from_token.user_id).await?;-- auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?;+ end_user_sessions(&state, &user_from_token.user_id).await?;auth::cookies::remove_cookie_response()}diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 9992c4a293..c956dd1c03 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -66,6 +66,7 @@ pub mod blacklist;pub mod cookies;pub mod decision;pub mod embedded;+pub mod idle_session;#[cfg(feature = "partial-auth")]mod detached;@@ -1636,6 +1637,9 @@ whereif payload.check_in_blacklist(state).await? {return Err(errors::ApiErrorResponse::InvalidJwtToken.into());}+ if payload.role_id.is_some() {+ idle_session::check_idle_session(&state.session_state(), &payload.user_id).await?;+ }authorization::check_tenant(payload.tenant_id.clone(),&state.session_state().tenant.tenant_id,@@ -5536,6 +5540,9 @@ wherestate: &A,) -> RouterResult<(AuthenticationData, AuthenticationType)> {let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;+ if payload.check_in_blacklist(state).await? {+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());+ }authorization::check_tenant(payload.tenant_id.clone(),&state.session_state().tenant.tenant_id,diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rsindex 68f1f756b9..8c936c2b33 100644--- a/crates/router/src/services/authentication/blacklist.rs+++ b/crates/router/src/services/authentication/blacklist.rs@@ -153,10 +153,16 @@ impl BlackList for AuthToken {whereA: SessionStateInfo + Sync,{- Ok(- check_user_in_blacklist(state, &self.user_id, self.exp).await?- || check_role_in_blacklist(state, &self.role_id, self.exp).await?,- )+ let is_blacklisted = check_user_in_blacklist(state, &self.user_id, self.exp).await?+ || check_role_in_blacklist(state, &self.role_id, self.exp).await?;++ // A login token that isn't blacklisted must also belong to a session that+ // hasn't gone idle.+ if !is_blacklisted {+ super::idle_session::check_idle_session(&state.session_state(), &self.user_id).await?;+ }++ Ok(is_blacklisted)}}diff --git a/crates/router/src/services/authentication/idle_session.rs b/crates/router/src/services/authentication/idle_session.rsnew file mode 100644index 0000000000..fb5e7f247e--- /dev/null+++ b/crates/router/src/services/authentication/idle_session.rs@@ -0,0 +1,74 @@+#[cfg(feature = "olap")]+use common_utils::date_time;+use error_stack::ResultExt;+use router_env::logger;++use crate::{+ consts::USER_IDLE_SESSION_PREFIX,+ core::errors::{ApiErrorResponse, RouterResult},+ routes::SessionState,+};+#[cfg(feature = "olap")]+use crate::{+ core::errors::{UserErrors, UserResult},+ utils::user::{end_user_sessions, get_redis_connection_for_global_tenant},+};++fn get_idle_session_key(user_id: &str) -> String {+ format!("{USER_IDLE_SESSION_PREFIX}{user_id}")+}++/// Starts the idle timer of a user who has just signed in.+#[cfg(feature = "olap")]+pub async fn start_idle_session(+ state: &SessionState,+ user_id: &str,+ idle_timeout_in_secs: u32,+) -> UserResult<()> {+ get_redis_connection_for_global_tenant(state)?+ .set_key_with_expiry(+ &get_idle_session_key(user_id).as_str().into(),+ date_time::now_unix_timestamp(),+ i64::from(idle_timeout_in_secs),+ )+ .await+ .change_context(UserErrors::InternalServerError)+}++/// Rejects a Dashboard login token once its user's idle timer has run out,+/// signing the user out the way signout does, and restarts the timer otherwise.+pub async fn check_idle_session(state: &SessionState, user_id: &str) -> RouterResult<()> {+ let Some(idle_timeout_in_secs) = state.conf.user.idle_session_timeout_in_secs else {+ return Ok(());+ };++ let redis_conn = state+ .global_store+ .get_redis_conn()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get redis connection")?;+ let key = get_idle_session_key(user_id);++ let is_session_active = redis_conn+ .exists::<()>(&key.as_str().into())+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to check the dashboard idle session")?;++ if !is_session_active {+ logger::info!(user_id, "Dashboard session expired due to inactivity");+ #[cfg(feature = "olap")]+ {+ let _ = end_user_sessions(state, user_id)+ .await+ .inspect_err(|error| logger::error!(?error, "Failed to end expired sessions"));+ }+ return Err(ApiErrorResponse::ExpiredJwtToken.into());+ }++ redis_conn+ .set_expiry(&key.as_str().into(), i64::from(idle_timeout_in_secs))+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to extend the dashboard idle session")+}diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rsindex 0cb921f41a..0937af23e7 100644--- a/crates/router/src/types/domain/user/decision_manager.rs+++ b/crates/router/src/types/domain/user/decision_manager.rs@@ -205,6 +205,15 @@ impl JWTFlow {new_lineage_context.clone(),);+ if let Some(idle_timeout_in_secs) = state.conf.user.idle_session_timeout_in_secs {+ auth::idle_session::start_idle_session(+ state,+ &new_lineage_context.user_id,+ idle_timeout_in_secs,+ )+ .await?;+ }+auth::AuthToken::new_token(new_lineage_context.user_id,new_lineage_context.merchant_id,diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rsindex be15b7370b..2213871577 100644--- a/crates/router/src/utils/user.rs+++ b/crates/router/src/utils/user.rs@@ -23,7 +23,7 @@ use crate::{core::errors::{StorageError, UserErrors, UserResult},routes::SessionState,services::{- authentication::{AuthToken, UserFromToken},+ authentication::{blacklist, AuthToken, UserFromToken},authorization::roles::RoleInfo,},types::{@@ -150,6 +150,17 @@ pub fn get_redis_connection_for_global_tenant(.attach_printable("Failed to get redis connection")}+/// Clears the user's recent 2FA verification state and blacklists every token+/// issued to them so far. Used by signout and when a Dashboard session expires+/// from inactivity.+pub async fn end_user_sessions(state: &SessionState, user_id: &str) -> UserResult<()> {+ two_factor_auth::delete_totp_from_redis(state, user_id).await?;+ two_factor_auth::delete_recovery_code_from_redis(state, user_id).await?;+ two_factor_auth::delete_totp_secret_from_redis(state, user_id).await?;++ blacklist::insert_user_in_blacklist(state, user_id).await+}+impl ForeignFrom<&user_api::AuthConfig> for UserAuthType {fn foreign_from(from: &user_api::AuthConfig) -> Self {match *from {