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(router): Add payment_session_id validation support to SdkAuthorization (#11583)
Anurag Thakur4ec618dca53b
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rsindex 2722e246b6..6f775ad393 100644--- a/crates/common_utils/src/id_type.rs+++ b/crates/common_utils/src/id_type.rs@@ -13,6 +13,7 @@ mod merchant;mod merchant_connector_account;mod organization;mod payment;+mod payment_session;mod payout;mod profile;mod profile_acquirer;@@ -56,6 +57,7 @@ pub use self::{merchant_connector_account::MerchantConnectorAccountId,organization::OrganizationId,payment::{PaymentId, PaymentReferenceId, PaymentResourceId},+ payment_session::PaymentSessionId,profile::ProfileId,profile_acquirer::ProfileAcquirerId,refunds::RefundReferenceId,diff --git a/crates/common_utils/src/id_type/payment_session.rs b/crates/common_utils/src/id_type/payment_session.rsnew file mode 100644index 0000000000..eb4d278c25--- /dev/null+++ b/crates/common_utils/src/id_type/payment_session.rs@@ -0,0 +1,10 @@+crate::id_type!(+ PaymentSessionId,+ "A type for payment_session_id that can be used for payment sessions"+);+crate::impl_id_type_methods!(PaymentSessionId, "payment_session_id");++// This is to display the `PaymentSessionId` as PaymentSessionId(abcd)+crate::impl_debug_id_type!(PaymentSessionId);+crate::impl_generate_id_id_type!(PaymentSessionId, "pay_sess");+crate::impl_try_from_cow_str_id_type!(PaymentSessionId, "payment_session_id");diff --git a/crates/hyperswitch_domain_models/src/sdk_auth.rs b/crates/hyperswitch_domain_models/src/sdk_auth.rsindex b50822c0ed..6ab6cdd6d3 100644--- a/crates/hyperswitch_domain_models/src/sdk_auth.rs+++ b/crates/hyperswitch_domain_models/src/sdk_auth.rs@@ -49,6 +49,7 @@ impl From<SdkAuthorizationContext> for Option<SdkAuthorization> {client_secret: input.client_secret,customer_id: input.customer_id,payment_method_session_id: input.payment_method_session_id,+ payment_session_id: None,})}Initiator::Admin | Initiator::Jwt { .. } | Initiator::EmbeddedToken { .. } => None, // SDK authorization is only applicable for API initiators@@ -81,6 +82,9 @@ pub struct SdkAuthorization {#[cfg(feature = "v2")]pub payment_method_session_id: Option<id_type::GlobalPaymentMethodSessionId>,++ /// Payment Session ID for SDK authorization validation+ pub payment_session_id: Option<id_type::PaymentSessionId>,}impl SdkAuthorization {@@ -104,6 +108,9 @@ impl SdkAuthorization {self.payment_method_session_id.as_ref().map(|id| format!("payment_method_session_id={}", id.get_string_repr())),+ self.payment_session_id+ .as_ref()+ .map(|id| format!("payment_session_id={}", id.get_string_repr())),].into_iter().flatten()@@ -202,6 +209,17 @@ impl SdkAuthorization {)},),+ payment_session_id: parts+ .get("payment_session_id")+ .map(|payment_session_id| {+ id_type::PaymentSessionId::try_from(std::borrow::Cow::from(+ payment_session_id.to_string(),+ ))+ .change_context(ValidationError::InvalidValue {+ message: "Invalid payment_session_id format".to_string(),+ })+ })+ .transpose()?,})}}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 324d6e9c5a..1092a646d3 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -220,6 +220,9 @@ pub const AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG: &str =/// Payment flow identifier used for performing GSM operationspub const PAYMENT_FLOW_STR: &str = "Payment";+/// Redis key prefix for payment session storage+pub(crate) const PAYMENT_SESSION_KEY_PREFIX: &str = "payment_session";+/// Default subflow identifier used for performing GSM operationspub const DEFAULT_SUBFLOW_STR: &str = "sub_flow";@@ -358,6 +361,8 @@ pub mod superposition {pub const DYNAMIC_FIELDS: &str = "dynamic_fields";/// payout sync tracker configuration keypub const PAYOUT_TRACKER_MAPPING: &str = "payout_tracker_mapping";+ /// payment session validation enabled configuration key+ pub const PAYMENT_SESSION_VALIDATION_ENABLED: &str = "payment_session_validation_enabled";}#[cfg(test)]diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex df15ad367f..7921fe6f60 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -165,3 +165,18 @@ config! {requires = DimensionsWithMerchantIdAndConnector,targeting_key = id_type::PayoutId}++config! {+ superposition_key = PAYMENT_SESSION_VALIDATION_ENABLED,+ output = bool,+ default = true,+ requires = DimensionsWithMerchantId,+ targeting_key = id_type::PaymentId+}++impl DatabaseBackedConfig for PaymentSessionValidationEnabled {+ const KEY: &'static str = "payment_session_validation_enabled";+ fn db_key(_dimensions: &impl super::dimension_state::DimensionsBase) -> Option<String> {+ None+ }+}diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rsindex 3ba369b647..48e1fb7e4c 100644--- a/crates/router/src/core/metrics.rs+++ b/crates/router/src/core/metrics.rs@@ -100,3 +100,8 @@ counter_metric!(GLOBAL_METER);counter_metric!(POST_AUTHENTICATION_TOKEN_PUSHED_TO_VGS, GLOBAL_METER);++// SDK Session Authorization Metrics+counter_metric!(SDK_AUTH_LEGACY_FLOW_TOTAL, GLOBAL_METER); // No. of SDK auth requests without session_id (legacy flow) - tracked per merchant_id+counter_metric!(SDK_AUTH_SESSION_VALIDATED_TOTAL, GLOBAL_METER); // No. of SDK auth requests with valid session_id - tracked per merchant_id+counter_metric!(SDK_AUTH_INVALID_SESSION_TOTAL, GLOBAL_METER); // No. of SDK auth requests with invalid session_id - tracked per merchant_iddiff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 24b3ebe4ec..724e647fe9 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -7,6 +7,7 @@ pub mod helpers;pub mod operations;pub mod session_token;+pub mod payment_session;#[cfg(feature = "retry")]pub mod retry;pub mod routing;@@ -8340,6 +8341,7 @@ wherepub is_manual_retry_enabled: Option<bool>,pub is_l2_l3_enabled: bool,pub external_authentication_data: Option<api_models::payments::ExternalThreeDsData>,+ pub payment_session_id: Option<id_type::PaymentSessionId>,}#[cfg(feature = "v1")]@@ -11881,6 +11883,9 @@ pub trait OperationSessionGetters<F> {#[cfg(feature = "v1")]fn get_is_manual_retry_enabled(&self) -> Option<bool>;+ #[cfg(feature = "v1")]+ fn get_payment_session_id(&self) -> Option<id_type::PaymentSessionId>;+#[cfg(feature = "v1")]fn get_installment_details(&self) -> Option<&common_types::payments::InstallmentData>;}@@ -12130,6 +12135,11 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> {self.payment_attempt.installment_data.as_ref()}+ #[cfg(feature = "v1")]+ fn get_payment_session_id(&self) -> Option<id_type::PaymentSessionId> {+ self.payment_session_id.clone()+ }+// #[cfg(feature = "v2")]// fn get_capture_method(&self) -> Option<enums::CaptureMethod> {// Some(self.payment_intent.capture_method)diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rsindex 8883de47f0..e63f6414e6 100644--- a/crates/router/src/core/payments/operations/payment_approve.rs+++ b/crates/router/src/core/payments/operations/payment_approve.rs@@ -202,6 +202,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRis_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rsindex 6bd2345d23..6a0c7075e0 100644--- a/crates/router/src/core/payments/operations/payment_cancel.rs+++ b/crates/router/src/core/payments/operations/payment_cancel.rs@@ -214,6 +214,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelReis_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rsindex aa78fadec6..43bbe2ee2a 100644--- a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs+++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs@@ -197,6 +197,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelPois_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rsindex 1ed7967acd..8cfe418c47 100644--- a/crates/router/src/core/payments/operations/payment_capture.rs+++ b/crates/router/src/core/payments/operations/payment_capture.rs@@ -270,6 +270,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymenis_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rsindex fbe92648cc..b72b16f00b 100644--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs@@ -376,6 +376,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>is_manual_retry_enabled: None,is_l2_l3_enabled: business_profile.is_l2_l3_enabled,external_authentication_data: None,+ payment_session_id: None,};let customer_details = Some(CustomerDetails {diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 0edcc4d6d3..8799222373 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -942,6 +942,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>is_manual_retry_enabled: business_profile.is_manual_retry_enabled,is_l2_l3_enabled: business_profile.is_l2_l3_enabled,external_authentication_data: request.three_ds_data.clone(),+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex 27ba6fd926..6b77f5dbc7 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -31,12 +31,15 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Validause crate::{consts,core::{- configs::dimension_state::DimensionsWithMerchantIdAndProfileId,+ configs::dimension_state::{Dimensions, DimensionsWithMerchantIdAndProfileId},errors::{self, CustomResult, RouterResult, StorageErrorExt},mandate::helpers as m_helpers,payment_link,payment_methods::transformers as pm_transformers,- payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},+ payments::{+ self, helpers, operations, payment_session::PaymentSessionManager, CustomerDetails,+ PaymentAddress, PaymentData,+ },utils as core_utils,},db::StorageInterface,@@ -625,6 +628,35 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>let unified_address = address.unify_with_payment_method_data_billing(add);+ // Check if payment session validation is enabled+ let dimensions = Dimensions::new()+ .with_merchant_id(platform.get_processor().get_account().get_id().clone());++ let session_validation_enabled = dimensions+ .get_payment_session_validation_enabled(+ state.store.as_ref(),+ state.superposition_service.as_deref(),+ None,+ )+ .await;++ // Generate payment session for the payment only if validation is enabled+ let payment_session_id = if session_validation_enabled {+ Some(+ PaymentSessionManager::create_session(+ state,+ platform.get_processor().get_account().get_id(),+ &payment_id,+ Some(session_expiry),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to create payment session")?,+ )+ } else {+ None+ };+let payment_data = PaymentData {flow: PhantomData,payment_intent,@@ -673,6 +705,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>is_manual_retry_enabled: None,is_l2_l3_enabled: business_profile.is_l2_l3_enabled,external_authentication_data: request.three_ds_data.clone(),+ payment_session_id,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rsindex 782c2c0c4f..128b9a54f3 100644--- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs+++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs@@ -182,6 +182,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSessis_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {operation: Box::new(self),diff --git a/crates/router/src/core/payments/operations/payment_recurrence.rs b/crates/router/src/core/payments/operations/payment_recurrence.rsindex f921d65ae2..df337e54fb 100644--- a/crates/router/src/core/payments/operations/payment_recurrence.rs+++ b/crates/router/src/core/payments/operations/payment_recurrence.rs@@ -386,6 +386,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>is_manual_retry_enabled: business_profile.is_manual_retry_enabled,is_l2_l3_enabled: business_profile.is_l2_l3_enabled,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rsindex 24040bb27d..7e8987bc0e 100644--- a/crates/router/src/core/payments/operations/payment_reject.rs+++ b/crates/router/src/core/payments/operations/payment_reject.rs@@ -201,6 +201,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequestis_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rsindex d638e7ba80..e5cd8d5141 100644--- a/crates/router/src/core/payments/operations/payment_session.rs+++ b/crates/router/src/core/payments/operations/payment_session.rs@@ -227,6 +227,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionRis_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rsindex fde642ffcc..46283c4709 100644--- a/crates/router/src/core/payments/operations/payment_start.rs+++ b/crates/router/src/core/payments/operations/payment_start.rs@@ -223,6 +223,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReqis_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rsindex 0e53b9359c..c11ed06235 100644--- a/crates/router/src/core/payments/operations/payment_status.rs+++ b/crates/router/src/core/payments/operations/payment_status.rs@@ -567,6 +567,7 @@ async fn get_tracker_for_sync<is_manual_retry_enabled: business_profile.is_manual_retry_enabled,is_l2_l3_enabled: business_profile.is_l2_l3_enabled,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rsindex ce9ad5a5e2..1002696295 100644--- a/crates/router/src/core/payments/operations/payment_update.rs+++ b/crates/router/src/core/payments/operations/payment_update.rs@@ -19,11 +19,14 @@ use router_env::{instrument, tracing};use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};use crate::{core::{- configs::dimension_state::DimensionsWithMerchantIdAndProfileId,+ configs::dimension_state::{Dimensions, DimensionsWithMerchantIdAndProfileId},errors::{self, CustomResult, RouterResult, StorageErrorExt},mandate::helpers as m_helpers,payment_methods::cards::create_encrypted_data,- payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},+ payments::{+ self, helpers, operations, payment_session::PaymentSessionManager, CustomerDetails,+ PaymentAddress, PaymentData,+ },utils as core_utils,},events::audit_events::{AuditEvent, AuditEventType},@@ -563,6 +566,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>is_manual_retry_enabled: None,is_l2_l3_enabled: business_profile.is_l2_l3_enabled,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {@@ -1077,6 +1081,44 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for).await.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;++ let processor_merchant_id = processor.get_account().get_id().clone();+ let payment_id = payment_data.payment_intent.payment_id.clone();++ // Check if payment session validation is enabled+ let dimensions = Dimensions::new().with_merchant_id(processor_merchant_id.clone());++ let session_validation_enabled = dimensions+ .get_payment_session_validation_enabled(+ state.store.as_ref(),+ state.superposition_service.as_deref(),+ None,+ )+ .await;++ // Recreate session only if validation is enabled+ if session_validation_enabled {+ let (new_payment_session_id, invalidation_report) =+ PaymentSessionManager::recreate_session(+ state,+ &processor_merchant_id,+ &payment_id,+ payment_data.payment_intent.session_expiry,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to refresh payment session during payment update")?;++ services::logger::debug!(+ payment_id = %payment_id.get_string_repr(),+ session_existed = invalidation_report.session_existed,+ "Payment session recreated during update"+ );++ // Update payment_data with new session_id+ payment_data.payment_session_id = Some(new_payment_session_id);+ }+let amount = payment_data.amount;req_state.event_contextdiff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rsindex fc2b127ab7..407afdb024 100644--- a/crates/router/src/core/payments/operations/payment_update_metadata.rs+++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs@@ -188,6 +188,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMeis_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {operation: Box::new(self),diff --git a/crates/router/src/core/payments/operations/payments_extend_authorization.rs b/crates/router/src/core/payments/operations/payments_extend_authorization.rsindex 39872df320..982ddb2784 100644--- a/crates/router/src/core/payments/operations/payments_extend_authorization.rs+++ b/crates/router/src/core/payments/operations/payments_extend_authorization.rs@@ -203,6 +203,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsExtendAuis_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rsindex 58fbc65290..d2e832dc0a 100644--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs@@ -182,6 +182,7 @@ impl<F: Send + Clone + Sync>is_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rsindex 0bba449a7a..90e52ea34a 100644--- a/crates/router/src/core/payments/operations/tax_calculation.rs+++ b/crates/router/src/core/payments/operations/tax_calculation.rs@@ -198,6 +198,7 @@ impl<F: Send + Clone + Sync>is_manual_retry_enabled: None,is_l2_l3_enabled: false,external_authentication_data: None,+ payment_session_id: None,};let get_trackers_response = operations::GetTrackerResponse {operation: Box::new(self),diff --git a/crates/router/src/core/payments/payment_session.rs b/crates/router/src/core/payments/payment_session.rsnew file mode 100644index 0000000000..2102842ca0--- /dev/null+++ b/crates/router/src/core/payments/payment_session.rs@@ -0,0 +1,272 @@+//! Core payment session ID management for SDK authorization.++use common_utils::{+ errors::CustomResult,+ id_type::{self, GenerateId, MerchantId, PaymentId},+};+use error_stack::ResultExt;+use router_env::{instrument, logger, tracing};+use serde::{Deserialize, Serialize};+use time::{Duration, PrimitiveDateTime};++use crate::{consts, db::errors, routes::app::SessionStateInfo};++/// Payment session data structure stored in Redis+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PaymentSessionData {+ /// SDK auth session ID+ pub payment_session_id: id_type::PaymentSessionId,+ /// Session creation time+ pub created_at: PrimitiveDateTime,+ /// Session expiry time+ pub expires_at: PrimitiveDateTime,+}++/// Report of session invalidation results+#[derive(Debug)]+pub struct SessionInvalidationReport {+ /// Whether a session existed and was deleted+ pub session_existed: bool,+}++/// Manager for payment session Redis operations+pub struct PaymentSessionManager;++impl PaymentSessionManager {+ /// Generate Redis key in format: payment_session:{processor_merchant_id}:{payment_id}+ /// We have a unique constraint on (processor_merchant_id, payment_id), so using them+ /// for creating the redis key+ fn get_session_key(processor_merchant_id: &MerchantId, payment_id: &PaymentId) -> String {+ format!(+ "{}:{}:{}",+ consts::PAYMENT_SESSION_KEY_PREFIX,+ processor_merchant_id.get_string_repr(),+ payment_id.get_string_repr()+ )+ }++ /// Create a new payment session and store in Redis with TTL+ ///+ /// # Arguments+ /// * `state` - Application state with Redis connection+ /// * `processor_merchant_id` - Merchant ID for the payment+ /// * `payment_id` - Payment ID for the session+ /// * `session_expiry` - Expiry time for the session+ ///+ /// # Returns+ /// The generated session ID string+ ///+ /// # Errors+ /// Returns error if Redis connection fails or TTL is invalid+ #[instrument(skip_all)]+ pub async fn create_session<S>(+ state: &S,+ processor_merchant_id: &MerchantId,+ payment_id: &PaymentId,+ session_expiry: Option<PrimitiveDateTime>,+ ) -> CustomResult<id_type::PaymentSessionId, errors::ApiErrorResponse>+ where+ S: SessionStateInfo + Sync,+ {+ let redis_conn = state+ .store()+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let session_expiry = session_expiry.unwrap_or_else(Self::get_default_session_expiry);++ // Generate a unique session ID+ let payment_session_id = id_type::PaymentSessionId::generate();++ let key = Self::get_session_key(processor_merchant_id, payment_id);++ // Calculate TTL in seconds from now until session_expiry+ let now = common_utils::date_time::now();+ let ttl_seconds = (session_expiry - now).whole_seconds();++ let ttl_seconds = if ttl_seconds > 0 {+ Ok(ttl_seconds)+ } else {+ Err(errors::ApiErrorResponse::PreconditionFailed {+ message: "Session expiry is in the past".to_string(),+ })+ }?;++ // Create session data structure+ let session_data = PaymentSessionData {+ payment_session_id: payment_session_id.clone(),+ created_at: now,+ expires_at: session_expiry,+ };++ // Store session data as JSON with TTL+ redis_conn+ .serialize_and_set_key_with_expiry(&key.into(), &session_data, ttl_seconds)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ logger::debug!(+ processor_merchant_id = %processor_merchant_id.get_string_repr(),+ payment_id = %payment_id.get_string_repr(),+ ttl_seconds,+ "Created payment session"+ );++ Ok(payment_session_id)+ }++ /// Get payment session data from Redis+ ///+ /// # Arguments+ /// * `state` - Application state with Redis connection+ /// * `processor_merchant_id` - Merchant ID for the payment+ /// * `payment_id` - Payment ID for the session+ ///+ /// # Returns+ /// Session data if found, None if not found or expired+ #[instrument(skip_all)]+ pub async fn get_session<S>(+ state: &S,+ processor_merchant_id: &MerchantId,+ payment_id: &PaymentId,+ ) -> CustomResult<Option<PaymentSessionData>, errors::ApiErrorResponse>+ where+ S: SessionStateInfo + Sync,+ {+ let redis_conn = state+ .store()+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let key = Self::get_session_key(processor_merchant_id, payment_id);++ match redis_conn+ .get_and_deserialize_key::<PaymentSessionData>(&key.into(), "PaymentSessionData")+ .await+ {+ Ok(session_data) => {+ logger::debug!(+ processor_merchant_id = %processor_merchant_id.get_string_repr(),+ payment_id = %payment_id.get_string_repr(),+ "Retrieved payment session"+ );+ Ok(Some(session_data))+ }++ Err(err) => {+ if matches!(err.current_context(), errors::RedisError::NotFound) {+ logger::debug!(+ processor_merchant_id = %processor_merchant_id.get_string_repr(),+ payment_id = %payment_id.get_string_repr(),+ "No payment session found"+ );+ Ok(None)+ } else {+ Err(err).change_context(errors::ApiErrorResponse::InternalServerError)+ }+ }+ }+ }++ /// Validate session ID against stored value+ ///+ /// # Arguments+ /// * `state` - Application state with Redis connection+ /// * `processor_merchant_id` - Merchant ID for the payment+ /// * `payment_id` - Payment ID for the session+ /// * `session_id` - Session ID to validate+ ///+ /// # Returns+ /// `true` if session exists and session_id matches+ #[instrument(skip_all)]+ pub async fn validate_session<S>(+ state: &S,+ processor_merchant_id: &MerchantId,+ payment_id: &PaymentId,+ payment_session_id: &id_type::PaymentSessionId,+ ) -> CustomResult<bool, errors::ApiErrorResponse>+ where+ S: SessionStateInfo + Sync,+ {+ let session = Self::get_session(state, processor_merchant_id, payment_id)+ .await+ .attach_printable("Unable to retrieve payment session")?;++ match session {+ Some(data) => {+ let is_valid = &data.payment_session_id == payment_session_id;+ logger::debug!(+ processor_merchant_id = %processor_merchant_id.get_string_repr(),+ payment_id = %payment_id.get_string_repr(),+ "Validated payment session"+ );+ Ok(is_valid)+ }+ None => {+ logger::error!(+ processor_merchant_id = %processor_merchant_id.get_string_repr(),+ payment_id = %payment_id.get_string_repr(),+ "Payment session not found for validation"+ );+ Ok(false)+ }+ }+ }++ /// Recreate payment session (invalidate old + create new)+ ///+ /// Convenience method that combines invalidate_session and create_session+ /// for payment update scenarios.+ ///+ /// # Arguments+ /// * `state` - Application state with Redis connection+ /// * `processor_merchant_id` - Merchant ID for the payment+ /// * `payment_id` - Payment ID for the session+ /// * `session_expiry` - Expiry time for the new session+ ///+ /// # Returns+ /// Tuple of (new_session_id, invalidation_report)+ #[instrument(skip_all)]+ pub async fn recreate_session<S>(+ state: &S,+ processor_merchant_id: &MerchantId,+ payment_id: &PaymentId,+ session_expiry: Option<PrimitiveDateTime>,+ ) -> CustomResult<+ (id_type::PaymentSessionId, SessionInvalidationReport),+ errors::ApiErrorResponse,+ >+ where+ S: SessionStateInfo + Sync,+ {+ let session_expiry = session_expiry.unwrap_or_else(Self::get_default_session_expiry);++ let session_existed = Self::get_session(state, processor_merchant_id, payment_id)+ .await?+ .is_some();++ let report = SessionInvalidationReport { session_existed };++ // Create new session, overwriting the previous value in redis+ let new_session_id = Self::create_session(+ state,+ processor_merchant_id,+ payment_id,+ Some(session_expiry),+ )+ .await?;++ logger::debug!(+ processor_merchant_id = %processor_merchant_id.get_string_repr(),+ payment_id = %payment_id.get_string_repr(),+ session_existed = report.session_existed,+ "Recreated payment session"+ );++ Ok((new_session_id, report))+ }++ fn get_default_session_expiry() -> PrimitiveDateTime {+ common_utils::date_time::now() + Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)+ }+}diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 40ab6775b6..77b77897aa 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -3985,6 +3985,7 @@ where.clone().get_required_value("client_secret")?,customer_id: payment_intent.customer_id.clone(),+ payment_session_id: payment_data.get_payment_session_id(),};let sdk_authorization = sdk_auth_datadiff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 1208d72489..a0a418928f 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -224,6 +224,7 @@ pub trait SessionStateInfo {fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])>;fn session_state(&self) -> SessionState;fn global_store(&self) -> Box<dyn GlobalStorageInterface>;+ fn superposition_service(&self) -> Option<Arc<SuperpositionClient>>;}impl SessionStateInfo for SessionState {@@ -283,6 +284,9 @@ impl SessionStateInfo for SessionState {fn global_store(&self) -> Box<dyn GlobalStorageInterface> {self.global_store.to_owned()}+ fn superposition_service(&self) -> Option<Arc<SuperpositionClient>> {+ self.superposition_service.clone()+ }}impl interfaces_helpers::GetComparisonServiceConfig for SessionState {diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 1aa2951f28..4a96fb33de 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -37,6 +37,8 @@ use super::jwt;use crate::configs::Settings;#[cfg(feature = "olap")]use crate::consts;+#[cfg(feature = "v1")]+use crate::core::configs::dimension_state::Dimensions;#[cfg(feature = "olap")]use crate::core::errors::UserResult;#[cfg(all(feature = "partial-auth", feature = "v1"))]@@ -47,6 +49,11 @@ use crate::{core::{api_keys,errors::{self, utils::StorageErrorExt, RouterResult},+ metrics::{+ SDK_AUTH_INVALID_SESSION_TOTAL, SDK_AUTH_LEGACY_FLOW_TOTAL,+ SDK_AUTH_SESSION_VALIDATED_TOTAL,+ },+ payments::payment_session::PaymentSessionManager,},headers,routes::app::SessionStateInfo,@@ -3429,6 +3436,81 @@ where).await?;+ // Taking processor_merchant_id for payment session validation as we have a unique constraint on (processor_merchant_id, payment_id)+ let processor_merchant_id = platform.get_processor().get_account().get_id();++ // Check if payment session validation is enabled+ let dimensions = Dimensions::new().with_merchant_id(processor_merchant_id.clone());++ let session_validation_enabled = dimensions+ .get_payment_session_validation_enabled(+ state.store().as_ref(),+ state.superposition_service().as_deref(),+ None,+ )+ .await;++ // Validate session_id if present and validation is enabled+ if session_validation_enabled {+ match sdk_auth.payment_session_id {+ Some(payment_session_id) => {+ let payment_id =+ crate::core::payments::helpers::get_payment_id_from_client_secret(+ &client_secret,+ )?;++ let payment_id = id_type::PaymentId::wrap(payment_id)+ .change_context(errors::ApiErrorResponse::Unauthorized)+ .attach_printable("Invalid payment_id in client_secret")?;++ // Validate session+ PaymentSessionManager::validate_session(+ state,+ processor_merchant_id,+ &payment_id,+ &payment_session_id,+ )+ .await+ .change_context(errors::ApiErrorResponse::Unauthorized)+ .attach_printable("Failed to validate payment session")?+ .then_some(())+ .ok_or_else(|| {+ SDK_AUTH_INVALID_SESSION_TOTAL.add(+ 1,+ &[router_env::opentelemetry::KeyValue::new(+ "merchant_id",+ processor_merchant_id.get_string_repr().to_string(),+ )],+ );+ report!(errors::ApiErrorResponse::Unauthorized)+ .attach_printable("Invalid Session ID")+ })?;++ SDK_AUTH_SESSION_VALIDATED_TOTAL.add(+ 1,+ &[router_env::opentelemetry::KeyValue::new(+ "merchant_id",+ processor_merchant_id.get_string_repr().to_string(),+ )],+ );+ }+ None => {+ // Legacy flow - no session_id provided+ SDK_AUTH_LEGACY_FLOW_TOTAL.add(+ 1,+ &[router_env::opentelemetry::KeyValue::new(+ "merchant_id",+ processor_merchant_id.get_string_repr().to_string(),+ )],+ );++ logger::info!("SDK auth without session_id - legacy flow");+ }+ }+ } else {+ logger::info!("Payment session validation is disabled");+ }+let profile = state.store().find_business_profile_by_merchant_id_profile_id(