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(authentication): kv flow introduction for authentication (#12611)
Shivansh Mathurce7e77892515
diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rsindex cd36de2ac5..f035faa7fe 100644--- a/crates/diesel_models/src/authentication.rs+++ b/crates/diesel_models/src/authentication.rs@@ -86,6 +86,40 @@ pub struct Authentication {pub shipping_country: Option<String>,pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,pub created_by: Option<String>,+ pub updated_by: Option<String>,+}++impl Authentication {+ /// Redis hash field key under which the authentication record is stored within its partition.+ pub fn get_hash_key_for_kv_store(+ authentication_id: &common_utils::id_type::AuthenticationId,+ ) -> String {+ format!("auth_{}", authentication_id.get_string_repr())+ }++ /// Reverse-lookup id to find an authentication by its id (scoped to the merchant).+ pub fn get_authentication_id_lookup_id(+ merchant_id: &common_utils::id_type::MerchantId,+ authentication_id: &common_utils::id_type::AuthenticationId,+ ) -> String {+ format!(+ "mid_{}_authn_id_{}",+ merchant_id.get_string_repr(),+ authentication_id.get_string_repr()+ )+ }++ /// Reverse-lookup id to find an authentication by its connector authentication id (webhook path).+ pub fn get_connector_authentication_lookup_id(+ merchant_id: &common_utils::id_type::MerchantId,+ connector_authentication_id: &str,+ ) -> String {+ format!(+ "mid_{}_conn_authn_{}",+ merchant_id.get_string_repr(),+ connector_authentication_id+ )+ }}#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Insertable)]@@ -166,6 +200,7 @@ pub struct AuthenticationNew {pub shipping_country: Option<String>,pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,pub created_by: Option<String>,+ pub updated_by: Option<String>,}#[derive(Debug)]@@ -173,6 +208,7 @@ pub enum AuthenticationUpdate {PreAuthenticationVersionCallUpdate {maximum_supported_3ds_version: common_utils::types::SemanticVersion,message_version: common_utils::types::SemanticVersion,+ updated_by: String,},PreAuthenticationThreeDsMethodCall {threeds_server_transaction_id: String,@@ -181,6 +217,7 @@ pub enum AuthenticationUpdate {acquirer_bin: Option<String>,acquirer_merchant_id: Option<String>,connector_metadata: Option<serde_json::Value>,+ updated_by: String,},PreAuthenticationUpdate {threeds_server_transaction_id: String,@@ -206,6 +243,7 @@ pub enum AuthenticationUpdate {shipping_country: Option<String>,earliest_supported_version: Option<common_utils::types::SemanticVersion>,latest_supported_version: Option<common_utils::types::SemanticVersion>,+ updated_by: String,},AuthenticationUpdate {trans_status: common_enums::TransactionStatus,@@ -228,6 +266,7 @@ pub enum AuthenticationUpdate {device_brand: Option<String>,device_os: Option<String>,device_display: Option<String>,+ updated_by: String,},PostAuthenticationUpdate {trans_status: common_enums::TransactionStatus,@@ -235,25 +274,30 @@ pub enum AuthenticationUpdate {authentication_status: common_enums::AuthenticationStatus,challenge_cancel: Option<String>,challenge_code_reason: Option<String>,+ updated_by: String,},ErrorUpdate {error_message: Option<String>,error_code: Option<String>,authentication_status: common_enums::AuthenticationStatus,connector_authentication_id: Option<String>,+ updated_by: String,},PostAuthorizationUpdate {authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,+ updated_by: String,},AuthenticationStatusUpdate {trans_status: common_enums::TransactionStatus,authentication_status: common_enums::AuthenticationStatus,+ updated_by: String,},/// Persists resolved acquirer details after bucket-based network lookup (eligibility_core)AcquirerDetailsUpdate {acquirer_bin: Option<String>,acquirer_merchant_id: Option<String>,acquirer_country_code: Option<String>,+ updated_by: String,},}@@ -319,6 +363,7 @@ impl Default for AuthenticationUpdateInternal {merchant_country_code: Default::default(),billing_country: Default::default(),shipping_country: Default::default(),+ updated_by: Default::default(),}}}@@ -386,10 +431,11 @@ pub struct AuthenticationUpdateInternal {pub merchant_country_code: Option<String>,pub billing_country: Option<String>,pub shipping_country: Option<String>,+ pub updated_by: String,}impl AuthenticationUpdateInternal {- pub fn apply_changeset(self, source: AuthenticationNew) -> Authentication {+ pub fn apply_changeset(self, source: Authentication) -> Authentication {let Self {connector_authentication_id,payment_method_id,@@ -450,6 +496,7 @@ impl AuthenticationUpdateInternal {merchant_country_code,billing_country,shipping_country,+ updated_by,} = self;Authentication {connector_authentication_id: connector_authentication_id@@ -532,6 +579,7 @@ impl AuthenticationUpdateInternal {shipping_country: shipping_country.or(source.shipping_country),processor_merchant_id: source.processor_merchant_id,created_by: source.created_by,+ updated_by: Some(updated_by),}}}@@ -544,6 +592,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {error_code,authentication_status,connector_authentication_id,+ updated_by,} => Self {error_code,error_message,@@ -554,10 +603,12 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {modified_at: common_utils::date_time::now(),payment_method_id: None,connector_metadata: None,+ updated_by,..Default::default()},AuthenticationUpdate::PostAuthorizationUpdate {authentication_lifecycle_status,+ updated_by,} => Self {connector_authentication_id: None,@@ -569,6 +620,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {error_message: None,error_code: None,connector_metadata: None,+ updated_by,..Default::default()},AuthenticationUpdate::PreAuthenticationUpdate {@@ -595,6 +647,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {shipping_country,earliest_supported_version,latest_supported_version,+ updated_by,} => Self {threeds_server_transaction_id: Some(threeds_server_transaction_id),maximum_supported_version: Some(maximum_supported_3ds_version),@@ -619,6 +672,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {shipping_country,earliest_supported_version,latest_supported_version,+ updated_by,..Default::default()},AuthenticationUpdate::AuthenticationUpdate {@@ -642,6 +696,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {device_brand,device_os,device_display,+ updated_by,} => Self {trans_status: Some(trans_status),authentication_type: Some(authentication_type),@@ -663,6 +718,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {device_brand,device_os,device_display,+ updated_by,..Default::default()},AuthenticationUpdate::PostAuthenticationUpdate {@@ -671,20 +727,24 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {authentication_status,challenge_cancel,challenge_code_reason,+ updated_by,} => Self {trans_status: Some(trans_status),eci,authentication_status: Some(authentication_status),challenge_cancel,challenge_code_reason,+ updated_by,..Default::default()},AuthenticationUpdate::PreAuthenticationVersionCallUpdate {maximum_supported_3ds_version,message_version,+ updated_by,} => Self {maximum_supported_version: Some(maximum_supported_3ds_version),message_version: Some(message_version),+ updated_by,..Default::default()},AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {@@ -694,6 +754,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {acquirer_bin,acquirer_merchant_id,connector_metadata,+ updated_by,} => Self {threeds_server_transaction_id: Some(threeds_server_transaction_id),three_ds_method_data,@@ -701,24 +762,29 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {acquirer_bin,acquirer_merchant_id,connector_metadata,+ updated_by,..Default::default()},AuthenticationUpdate::AuthenticationStatusUpdate {trans_status,authentication_status,+ updated_by,} => Self {trans_status: Some(trans_status),authentication_status: Some(authentication_status),+ updated_by,..Default::default()},AuthenticationUpdate::AcquirerDetailsUpdate {acquirer_bin,acquirer_merchant_id,acquirer_country_code,+ updated_by,} => Self {acquirer_bin,acquirer_merchant_id,acquirer_country_code,+ updated_by,..Default::default()},}diff --git a/crates/diesel_models/src/kv/entity_type.rs b/crates/diesel_models/src/kv/entity_type.rsindex b2bdec2f37..7ebbf79376 100644--- a/crates/diesel_models/src/kv/entity_type.rs+++ b/crates/diesel_models/src/kv/entity_type.rs@@ -54,6 +54,10 @@ entity_type! {"reverse_lookup" => {crate::reverse_lookup::ReverseLookupNew,}+ "authentication" => {+ crate::authentication::AuthenticationNew,+ crate::authentication::AuthenticationUpdateInternal,+ }"capture" => {crate::capture::CaptureNew,crate::capture::CaptureUpdateInternal,diff --git a/crates/diesel_models/src/query/authentication.rs b/crates/diesel_models/src/query/authentication.rsindex 4bd6bbdc32..6c3e9342df 100644--- a/crates/diesel_models/src/query/authentication.rs+++ b/crates/diesel_models/src/query/authentication.rs@@ -2,10 +2,8 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};use super::generics;use crate::{- authentication::{- Authentication, AuthenticationNew, AuthenticationUpdate, AuthenticationUpdateInternal,- },- errors,+ authentication::{Authentication, AuthenticationNew, AuthenticationUpdateInternal},+ errors, kv,schema::authentication::dsl,PgPooledConn, StorageResult,};@@ -14,14 +12,21 @@ impl AuthenticationNew {pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authentication> {generics::generic_insert(conn, self).await}++ pub async fn generate_drainer_insert_query(+ self,+ conn: &mut PgPooledConn,+ ) -> StorageResult<kv::SerializableQuery> {+ kv::generate_insert_query(conn, self).await+ }}impl Authentication {pub async fn update_by_merchant_id_authentication_id(conn: &PgPooledConn,- merchant_id: common_utils::id_type::MerchantId,- authentication_id: common_utils::id_type::AuthenticationId,- authorization_update: AuthenticationUpdate,+ merchant_id: &common_utils::id_type::MerchantId,+ authentication_id: &common_utils::id_type::AuthenticationId,+ authentication_update: AuthenticationUpdateInternal,) -> StorageResult<Self> {match generics::generic_update_with_unique_predicate_get_result::<<Self as HasTable>::Table,@@ -33,7 +38,7 @@ impl Authentication {dsl::merchant_id.eq(merchant_id.to_owned()).and(dsl::authentication_id.eq(authentication_id.to_owned())),- AuthenticationUpdateInternal::from(authorization_update),+ authentication_update,).await{@@ -84,3 +89,21 @@ impl Authentication {.await}}++impl AuthenticationUpdateInternal {+ pub async fn generate_drainer_update_query(+ self,+ conn: &mut PgPooledConn,+ merchant_id: common_utils::id_type::MerchantId,+ authentication_id: common_utils::id_type::AuthenticationId,+ ) -> StorageResult<kv::SerializableQuery> {+ kv::generate_update_query_with_predicate::<<Authentication as HasTable>::Table, _, _>(+ conn,+ dsl::merchant_id+ .eq(merchant_id)+ .and(dsl::authentication_id.eq(authentication_id)),+ self,+ )+ .await+ }+}diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 0cf3a5d0ca..d256b80b20 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -181,6 +181,8 @@ diesel::table! {processor_merchant_id -> Nullable<Varchar>,#[max_length = 255]created_by -> Nullable<Varchar>,+ #[max_length = 32]+ updated_by -> Nullable<Varchar>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 0443531dcc..2566723946 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -181,6 +181,8 @@ diesel::table! {processor_merchant_id -> Nullable<Varchar>,#[max_length = 255]created_by -> Nullable<Varchar>,+ #[max_length = 32]+ updated_by -> Nullable<Varchar>,}}diff --git a/crates/hyperswitch_domain_models/src/authentication.rs b/crates/hyperswitch_domain_models/src/authentication.rsindex ce154117e8..1089e4571c 100644--- a/crates/hyperswitch_domain_models/src/authentication.rs+++ b/crates/hyperswitch_domain_models/src/authentication.rs@@ -1,20 +1,25 @@use std::str::FromStr;+use async_trait::async_trait;use common_enums::MerchantCategoryCode;use common_utils::{crypto::Encryptable,encryption::Encryption,errors::{CustomResult, ValidationError},pii,- types::keymanager::ToEncryptable,+ types::keymanager::{Identifier, KeyManagerState, ToEncryptable},};use error_stack::ResultExt;-use hyperswitch_masking::Secret;+use hyperswitch_masking::{PeekInterface, Secret};use rustc_hash::FxHashMap;use serde_json::Value;-use crate::router_request_types::unified_authentication_service::{- DynamicData, PostAuthenticationDetails,+use super::behaviour;+use crate::{+ router_request_types::unified_authentication_service::{+ DynamicData, PostAuthenticationDetails,+ },+ type_encryption::{crypto_operation, AsyncLift, CryptoOperation},};#[derive(Clone, Debug, router_derive::ToEncryption, serde::Serialize)]@@ -98,9 +103,20 @@ pub struct Authentication {pub merchant_country_code: Option<String>,pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,pub created_by: Option<common_utils::types::CreatedBy>,+ pub updated_by: Option<String>,}impl Authentication {+ /// Records which storage layer (KV / Postgres) wrote this row; the previous value+ /// drives KV-vs-Postgres routing on later updates in `decide_storage_scheme`.+ pub fn update_storage_scheme(+ mut self,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> Self {+ self.updated_by = Some(storage_scheme.to_string());+ self+ }+pub fn is_separate_authn_required(&self) -> bool {self.maximum_supported_version.as_ref()@@ -152,10 +168,321 @@ pub struct PgRedirectResponseForAuthentication {pub amount: Option<common_utils::types::MinorUnit>,}+#[async_trait]+impl behaviour::Conversion for Authentication {+ type DstType = diesel_models::authentication::Authentication;+ type NewDstType = diesel_models::authentication::AuthenticationNew;++ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {+ Ok(Self::DstType {+ authentication_id: self.authentication_id,+ merchant_id: self.merchant_id,+ authentication_connector: self.authentication_connector,+ connector_authentication_id: self.connector_authentication_id,+ authentication_data: self.authentication_data,+ payment_method_id: self.payment_method_id,+ authentication_type: self.authentication_type,+ authentication_status: self.authentication_status,+ authentication_lifecycle_status: self.authentication_lifecycle_status,+ created_at: self.created_at,+ modified_at: self.modified_at,+ error_message: self.error_message,+ error_code: self.error_code,+ connector_metadata: self.connector_metadata,+ maximum_supported_version: self.maximum_supported_version,+ threeds_server_transaction_id: self.threeds_server_transaction_id,+ cavv: self.cavv,+ authentication_flow_type: self.authentication_flow_type,+ message_version: self.message_version,+ eci: self.eci,+ trans_status: self.trans_status,+ acquirer_bin: self.acquirer_bin,+ acquirer_merchant_id: self.acquirer_merchant_id,+ three_ds_method_data: self.three_ds_method_data,+ three_ds_method_url: self.three_ds_method_url,+ acs_url: self.acs_url,+ challenge_request: self.challenge_request,+ acs_reference_number: self.acs_reference_number,+ acs_trans_id: self.acs_trans_id,+ acs_signed_content: self.acs_signed_content,+ profile_id: self.profile_id,+ payment_id: self.payment_id,+ merchant_connector_id: self.merchant_connector_id,+ ds_trans_id: self.ds_trans_id,+ directory_server_id: self.directory_server_id,+ acquirer_country_code: self.acquirer_country_code,+ service_details: self.service_details,+ organization_id: self.organization_id,+ authentication_client_secret: self.authentication_client_secret,+ force_3ds_challenge: self.force_3ds_challenge,+ psd2_sca_exemption_type: self.psd2_sca_exemption_type,+ return_url: self.return_url,+ amount: self.amount,+ currency: self.currency,+ billing_address: self.billing_address.map(Encryption::from),+ shipping_address: self.shipping_address.map(Encryption::from),+ browser_info: self.browser_info,+ email: self.email.map(|email| email.into()),+ profile_acquirer_id: self.profile_acquirer_id,+ challenge_code: self.challenge_code,+ challenge_cancel: self.challenge_cancel,+ challenge_code_reason: self.challenge_code_reason,+ message_extension: self.message_extension,+ challenge_request_key: self.challenge_request_key,+ customer_details: self.customer_details,+ earliest_supported_version: self.earliest_supported_version,+ latest_supported_version: self.latest_supported_version,+ mcc: self.mcc,+ platform: self.platform.map(|platform| platform.to_string()),+ device_type: self.device_type,+ device_brand: self.device_brand,+ device_os: self.device_os,+ device_display: self.device_display,+ browser_name: self.browser_name,+ browser_version: self.browser_version,+ scheme_name: self.scheme_name,+ exemption_requested: self.exemption_requested,+ exemption_accepted: self.exemption_accepted,+ issuer_id: self.issuer_id,+ issuer_country: self.issuer_country,+ merchant_country_code: self.merchant_country_code,+ billing_country: self.billing_country,+ shipping_country: self.shipping_country,+ processor_merchant_id: self.processor_merchant_id,+ created_by: self.created_by.map(|created_by| created_by.to_string()),+ updated_by: self.updated_by,+ })+ }++ async fn convert_back(+ state: &KeyManagerState,+ other: Self::DstType,+ key: &Secret<Vec<u8>>,+ key_manager_identifier: Identifier,+ ) -> CustomResult<Self, ValidationError> {+ let batch_decrypted = crypto_operation(+ state,+ common_utils::type_name!(Self),+ CryptoOperation::BatchDecrypt(EncryptedAuthentication::to_encryptable(+ EncryptedAuthentication {+ billing_address: other.billing_address,+ shipping_address: other.shipping_address,+ },+ )),+ key_manager_identifier.clone(),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting authentication data".to_string(),+ })?;++ let decrypted_data =+ FromRequestEncryptableAuthentication::from_encryptable(batch_decrypted)+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting authentication data".to_string(),+ })?;++ let email_decrypted = other+ .clone()+ .async_lift(|inner| async {+ crypto_operation::<String, pii::EmailStrategy>(+ state,+ common_utils::type_name!(Self),+ CryptoOperation::DecryptOptional(inner),+ key_manager_identifier.clone(),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting authentication email".to_string(),+ })?;++ Ok(Self {+ authentication_id: other.authentication_id,+ merchant_id: other.merchant_id,+ authentication_connector: other.authentication_connector,+ connector_authentication_id: other.connector_authentication_id,+ authentication_data: other.authentication_data,+ payment_method_id: other.payment_method_id,+ authentication_type: other.authentication_type,+ authentication_status: other.authentication_status,+ authentication_lifecycle_status: other.authentication_lifecycle_status,+ created_at: other.created_at,+ modified_at: other.modified_at,+ error_message: other.error_message,+ error_code: other.error_code,+ connector_metadata: other.connector_metadata,+ maximum_supported_version: other.maximum_supported_version,+ threeds_server_transaction_id: other.threeds_server_transaction_id,+ cavv: other.cavv,+ authentication_flow_type: other.authentication_flow_type,+ message_version: other.message_version,+ eci: other.eci,+ trans_status: other.trans_status,+ acquirer_bin: other.acquirer_bin,+ acquirer_merchant_id: other.acquirer_merchant_id,+ three_ds_method_data: other.three_ds_method_data,+ three_ds_method_url: other.three_ds_method_url,+ acs_url: other.acs_url,+ challenge_request: other.challenge_request,+ acs_reference_number: other.acs_reference_number,+ acs_trans_id: other.acs_trans_id,+ acs_signed_content: other.acs_signed_content,+ profile_id: other.profile_id,+ payment_id: other.payment_id,+ merchant_connector_id: other.merchant_connector_id,+ ds_trans_id: other.ds_trans_id,+ directory_server_id: other.directory_server_id,+ acquirer_country_code: other.acquirer_country_code,+ organization_id: other.organization_id,+ mcc: other.mcc,+ amount: other.amount,+ currency: other.currency,+ issuer_country: other.issuer_country,+ earliest_supported_version: other.earliest_supported_version,+ latest_supported_version: other.latest_supported_version,+ platform: other+ .platform+ .as_deref()+ .map(|s| {+ api_models::payments::DeviceChannel::from_str(s).change_context(+ ValidationError::InvalidValue {+ message: "Invalid device channel".into(),+ },+ )+ })+ .transpose()?,+ device_type: other.device_type,+ device_brand: other.device_brand,+ device_os: other.device_os,+ device_display: other.device_display,+ browser_name: other.browser_name,+ browser_version: other.browser_version,+ issuer_id: other.issuer_id,+ scheme_name: other.scheme_name,+ exemption_requested: other.exemption_requested,+ exemption_accepted: other.exemption_accepted,+ service_details: other.service_details,+ authentication_client_secret: other.authentication_client_secret,+ force_3ds_challenge: other.force_3ds_challenge,+ psd2_sca_exemption_type: other.psd2_sca_exemption_type,+ return_url: other.return_url,+ billing_address: decrypted_data.billing_address,+ shipping_address: decrypted_data.shipping_address,+ browser_info: other.browser_info,+ email: email_decrypted,+ profile_acquirer_id: other.profile_acquirer_id,+ challenge_code: other.challenge_code,+ challenge_cancel: other.challenge_cancel,+ challenge_code_reason: other.challenge_code_reason,+ message_extension: other.message_extension,+ challenge_request_key: other.challenge_request_key,+ customer_details: other.customer_details,+ billing_country: other.billing_country,+ shipping_country: other.shipping_country,+ merchant_country_code: other.merchant_country_code,+ processor_merchant_id: other.processor_merchant_id,+ created_by: other+ .created_by+ .and_then(|created_by| created_by.parse::<common_utils::types::CreatedBy>().ok()),+ updated_by: other.updated_by,+ })+ }++ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {+ Ok(Self::NewDstType {+ authentication_id: self.authentication_id,+ merchant_id: self.merchant_id,+ authentication_connector: self.authentication_connector,+ connector_authentication_id: self.connector_authentication_id,+ payment_method_id: self.payment_method_id,+ authentication_type: self.authentication_type,+ authentication_status: self.authentication_status,+ authentication_lifecycle_status: self.authentication_lifecycle_status,+ error_message: self.error_message,+ error_code: self.error_code,+ connector_metadata: self.connector_metadata,+ maximum_supported_version: self.maximum_supported_version,+ threeds_server_transaction_id: self.threeds_server_transaction_id,+ cavv: self.cavv,+ authentication_flow_type: self.authentication_flow_type,+ message_version: self.message_version,+ eci: self.eci,+ trans_status: self.trans_status,+ acquirer_bin: self.acquirer_bin,+ acquirer_merchant_id: self.acquirer_merchant_id,+ three_ds_method_data: self.three_ds_method_data,+ three_ds_method_url: self.three_ds_method_url,+ acs_url: self.acs_url,+ challenge_request: self.challenge_request,+ acs_reference_number: self.acs_reference_number,+ acs_trans_id: self.acs_trans_id,+ acs_signed_content: self.acs_signed_content,+ profile_id: self.profile_id,+ payment_id: self.payment_id,+ merchant_connector_id: self.merchant_connector_id,+ ds_trans_id: self.ds_trans_id,+ directory_server_id: self.directory_server_id,+ acquirer_country_code: self.acquirer_country_code,+ service_details: self.service_details,+ organization_id: self.organization_id,+ authentication_client_secret: self.authentication_client_secret,+ force_3ds_challenge: self.force_3ds_challenge,+ psd2_sca_exemption_type: self.psd2_sca_exemption_type,+ return_url: self.return_url,+ amount: self.amount,+ currency: self.currency,+ billing_address: self.billing_address.map(Encryption::from),+ shipping_address: self.shipping_address.map(Encryption::from),+ browser_info: self.browser_info,+ email: self.email.map(|email| email.into()),+ profile_acquirer_id: self.profile_acquirer_id,+ challenge_code: self.challenge_code,+ challenge_cancel: self.challenge_cancel,+ challenge_code_reason: self.challenge_code_reason,+ message_extension: self.message_extension,+ challenge_request_key: self.challenge_request_key,+ customer_details: self.customer_details,+ earliest_supported_version: self.earliest_supported_version,+ latest_supported_version: self.latest_supported_version,+ mcc: self.mcc,+ platform: self.platform.map(|platform| platform.to_string()),+ device_type: self.device_type,+ device_brand: self.device_brand,+ device_os: self.device_os,+ device_display: self.device_display,+ browser_name: self.browser_name,+ browser_version: self.browser_version,+ scheme_name: self.scheme_name,+ exemption_requested: self.exemption_requested,+ exemption_accepted: self.exemption_accepted,+ issuer_id: self.issuer_id,+ issuer_country: self.issuer_country,+ merchant_country_code: self.merchant_country_code,+ created_at: self.created_at,+ modified_at: self.modified_at,+ authentication_data: self.authentication_data,+ billing_country: self.billing_country,+ shipping_country: self.shipping_country,+ processor_merchant_id: self.processor_merchant_id,+ created_by: self.created_by.map(|created_by| created_by.to_string()),+ updated_by: self.updated_by,+ })+ }+}++#[derive(Debug)]pub enum AuthenticationUpdate {PreAuthenticationVersionCallUpdate {maximum_supported_3ds_version: common_utils::types::SemanticVersion,message_version: common_utils::types::SemanticVersion,+ updated_by: String,},PreAuthenticationThreeDsMethodCall {threeds_server_transaction_id: String,@@ -164,6 +491,7 @@ pub enum AuthenticationUpdate {acquirer_bin: Option<String>,acquirer_merchant_id: Option<String>,connector_metadata: Option<Value>,+ updated_by: String,},PreAuthenticationUpdate {threeds_server_transaction_id: String,@@ -189,6 +517,7 @@ pub enum AuthenticationUpdate {shipping_country: Option<String>,earliest_supported_version: Option<common_utils::types::SemanticVersion>,latest_supported_version: Option<common_utils::types::SemanticVersion>,+ updated_by: String,},AuthenticationUpdate {trans_status: common_enums::TransactionStatus,@@ -211,6 +540,7 @@ pub enum AuthenticationUpdate {device_brand: Option<String>,device_os: Option<String>,device_display: Option<String>,+ updated_by: String,},PostAuthenticationUpdate {trans_status: common_enums::TransactionStatus,@@ -218,19 +548,23 @@ pub enum AuthenticationUpdate {authentication_status: common_enums::AuthenticationStatus,challenge_cancel: Option<String>,challenge_code_reason: Option<String>,+ updated_by: String,},ErrorUpdate {error_message: Option<String>,error_code: Option<String>,authentication_status: common_enums::AuthenticationStatus,connector_authentication_id: Option<String>,+ updated_by: String,},PostAuthorizationUpdate {authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,+ updated_by: String,},AuthenticationStatusUpdate {trans_status: common_enums::TransactionStatus,authentication_status: common_enums::AuthenticationStatus,+ updated_by: String,},/// Used after bucket-based acquirer resolution in authentication_eligibility_core/// to persist the dynamically resolved acquirer details back to the authentication record.@@ -238,5 +572,230 @@ pub enum AuthenticationUpdate {acquirer_bin: Option<String>,acquirer_merchant_id: Option<String>,acquirer_country_code: Option<String>,+ updated_by: String,},}++impl From<AuthenticationUpdate> for diesel_models::authentication::AuthenticationUpdate {+ fn from(authentication_update: AuthenticationUpdate) -> Self {+ match authentication_update {+ AuthenticationUpdate::PreAuthenticationVersionCallUpdate {+ maximum_supported_3ds_version,+ message_version,+ updated_by,+ } => Self::PreAuthenticationVersionCallUpdate {+ maximum_supported_3ds_version,+ message_version,+ updated_by,+ },+ AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {+ threeds_server_transaction_id,+ three_ds_method_data,+ three_ds_method_url,+ acquirer_bin,+ acquirer_merchant_id,+ connector_metadata,+ updated_by,+ } => Self::PreAuthenticationThreeDsMethodCall {+ threeds_server_transaction_id,+ three_ds_method_data,+ three_ds_method_url,+ acquirer_bin,+ acquirer_merchant_id,+ connector_metadata,+ updated_by,+ },+ AuthenticationUpdate::PreAuthenticationUpdate {+ threeds_server_transaction_id,+ maximum_supported_3ds_version,+ connector_authentication_id,+ three_ds_method_data,+ three_ds_method_url,+ message_version,+ connector_metadata,+ authentication_status,+ acquirer_bin,+ acquirer_merchant_id,+ directory_server_id,+ acquirer_country_code,+ billing_address,+ shipping_address,+ browser_info,+ email,+ scheme_id,+ merchant_category_code,+ merchant_country_code,+ billing_country,+ shipping_country,+ earliest_supported_version,+ latest_supported_version,+ updated_by,+ } => Self::PreAuthenticationUpdate {+ threeds_server_transaction_id,+ maximum_supported_3ds_version,+ connector_authentication_id,+ three_ds_method_data,+ three_ds_method_url,+ message_version,+ connector_metadata,+ authentication_status,+ acquirer_bin,+ acquirer_merchant_id,+ directory_server_id,+ acquirer_country_code,+ billing_address: billing_address.map(|billing_address| billing_address.into()),+ shipping_address: shipping_address.map(|shipping_address| shipping_address.into()),+ browser_info,+ email: email.map(|email| email.into()),+ scheme_id,+ merchant_category_code,+ merchant_country_code,+ billing_country,+ shipping_country,+ earliest_supported_version,+ latest_supported_version,+ updated_by,+ },+ AuthenticationUpdate::AuthenticationUpdate {+ trans_status,+ authentication_type,+ acs_url,+ challenge_request,+ acs_reference_number,+ acs_trans_id,+ acs_signed_content,+ connector_metadata,+ authentication_status,+ ds_trans_id,+ eci,+ challenge_code,+ challenge_cancel,+ challenge_code_reason,+ message_extension,+ challenge_request_key,+ device_type,+ device_brand,+ device_os,+ device_display,+ updated_by,+ } => Self::AuthenticationUpdate {+ trans_status,+ authentication_type,+ acs_url,+ challenge_request,+ acs_reference_number,+ acs_trans_id,+ acs_signed_content,+ connector_metadata,+ authentication_status,+ ds_trans_id,+ eci,+ challenge_code,+ challenge_cancel,+ challenge_code_reason,+ message_extension,+ challenge_request_key,+ device_type,+ device_brand,+ device_os,+ device_display,+ updated_by,+ },+ AuthenticationUpdate::PostAuthenticationUpdate {+ trans_status,+ eci,+ authentication_status,+ challenge_cancel,+ challenge_code_reason,+ updated_by,+ } => Self::PostAuthenticationUpdate {+ trans_status,+ eci,+ authentication_status,+ challenge_cancel,+ challenge_code_reason,+ updated_by,+ },+ AuthenticationUpdate::ErrorUpdate {+ error_message,+ error_code,+ authentication_status,+ connector_authentication_id,+ updated_by,+ } => Self::ErrorUpdate {+ error_message,+ error_code,+ authentication_status,+ connector_authentication_id,+ updated_by,+ },+ AuthenticationUpdate::PostAuthorizationUpdate {+ authentication_lifecycle_status,+ updated_by,+ } => Self::PostAuthorizationUpdate {+ authentication_lifecycle_status,+ updated_by,+ },+ AuthenticationUpdate::AuthenticationStatusUpdate {+ trans_status,+ authentication_status,+ updated_by,+ } => Self::AuthenticationStatusUpdate {+ trans_status,+ authentication_status,+ updated_by,+ },+ AuthenticationUpdate::AcquirerDetailsUpdate {+ acquirer_bin,+ acquirer_merchant_id,+ acquirer_country_code,+ updated_by,+ } => Self::AcquirerDetailsUpdate {+ acquirer_bin,+ acquirer_merchant_id,+ acquirer_country_code,+ updated_by,+ },+ }+ }+}++#[async_trait]+pub trait AuthenticationInterface {+ type Error;++ async fn insert_authentication(+ &self,+ state: &KeyManagerState,+ merchant_key_store: &crate::merchant_key_store::MerchantKeyStore,+ authentication: Authentication,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> CustomResult<Authentication, Self::Error>;++ async fn find_authentication_by_merchant_id_authentication_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ authentication_id: &common_utils::id_type::AuthenticationId,+ merchant_key_store: &crate::merchant_key_store::MerchantKeyStore,+ state: &KeyManagerState,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> CustomResult<Authentication, Self::Error>;++ async fn find_authentication_by_merchant_id_connector_authentication_id(+ &self,+ merchant_id: common_utils::id_type::MerchantId,+ connector_authentication_id: String,+ merchant_key_store: &crate::merchant_key_store::MerchantKeyStore,+ state: &KeyManagerState,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> CustomResult<Authentication, Self::Error>;++ async fn update_authentication_by_merchant_id_authentication_id(+ &self,+ previous_state: Authentication,+ authentication_update: AuthenticationUpdate,+ merchant_key_store: &crate::merchant_key_store::MerchantKeyStore,+ state: &KeyManagerState,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> CustomResult<Authentication, Self::Error>;+}diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rsindex eaf17b24c6..034f4fd151 100644--- a/crates/router/src/core/authentication.rs+++ b/crates/router/src/core/authentication.rs@@ -47,6 +47,7 @@ pub async fn perform_authentication(payment_id: common_utils::id_type::PaymentId,force_3ds_challenge: bool,merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,+ storage_scheme: diesel_models::enums::MerchantStorageScheme,) -> CustomResult<api::authentication::AuthenticationResponse, ApiErrorResponse> {let router_data = transformers::construct_authentication_router_data(state,@@ -98,6 +99,7 @@ pub async fn perform_authentication(None,merchant_key_store,authentication_info,+ storage_scheme,)).await?;response@@ -138,6 +140,7 @@ pub async fn perform_post_authentication(&authentication_id,processor.get_key_store(),key_state,+ processor.get_account().storage_scheme,).await.to_not_found_response(ApiErrorResponse::InternalServerError)@@ -185,6 +188,7 @@ pub async fn perform_post_authentication(None,processor.get_key_store(),authentication_info,+ processor.get_account().storage_scheme,).await?} else {@@ -289,6 +293,7 @@ pub async fn perform_pre_authentication(acquirer_details.clone(),processor.get_key_store(),authentication_info,+ processor.get_account().storage_scheme,)).await?;// from version call response, we will get to know the maximum supported 3ds version.@@ -338,6 +343,7 @@ pub async fn perform_pre_authentication(acquirer_details,processor.get_key_store(),authentication_info,+ processor.get_account().storage_scheme,)).await?;diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rsindex 40b5fc48c3..e1c6ff73be 100644--- a/crates/router/src/core/authentication/transformers.rs+++ b/crates/router/src/core/authentication/transformers.rs@@ -367,6 +367,7 @@ implmerchant_country_code: None,processor_merchant_id: None,created_by: None,+ updated_by: None,}}}@@ -491,6 +492,7 @@ implmerchant_country_code: None,processor_merchant_id: None,created_by: None,+ updated_by: None,}}}diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rsindex 242a589aae..1078d2a35e 100644--- a/crates/router/src/core/authentication/utils.rs+++ b/crates/router/src/core/authentication/utils.rs@@ -63,6 +63,7 @@ pub async fn update_trackers<F: Clone, Req>(acquirer_details: Option<super::types::AcquirerDetails>,merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,authentication_info: router_request_types::authentication::AuthenticationInfo,+ storage_scheme: diesel_models::enums::MerchantStorageScheme,) -> RouterResult<authentication::Authentication> {let key_manager_state = state.into();let authentication_update = match router_data.response {@@ -204,6 +205,7 @@ pub async fn update_trackers<F: Clone, Req>(),earliest_supported_version: Some(maximum_supported_3ds_version.clone()),latest_supported_version: Some(maximum_supported_3ds_version.clone()),+ updated_by: storage_scheme.to_string(),}}AuthenticationResponseData::AuthNResponse {@@ -270,6 +272,7 @@ pub async fn update_trackers<F: Clone, Req>(.device_details.as_ref().and_then(|device_details| device_details.device_display.clone()),+ updated_by: storage_scheme.to_string(),}}AuthenticationResponseData::PostAuthNResponse {@@ -302,6 +305,7 @@ pub async fn update_trackers<F: Clone, Req>(eci,challenge_cancel,challenge_code_reason,+ updated_by: storage_scheme.to_string(),}}AuthenticationResponseData::PreAuthVersionCallResponse {@@ -309,6 +313,7 @@ pub async fn update_trackers<F: Clone, Req>(} => authentication::AuthenticationUpdate::PreAuthenticationVersionCallUpdate {message_version: maximum_supported_3ds_version.clone(),maximum_supported_3ds_version,+ updated_by: storage_scheme.to_string(),},AuthenticationResponseData::PreAuthThreeDsMethodCallResponse {threeds_server_transaction_id,@@ -325,6 +330,7 @@ pub async fn update_trackers<F: Clone, Req>(.map(|acquirer_details| acquirer_details.acquirer_bin.clone()),acquirer_merchant_id: acquirer_details.map(|acquirer_details| acquirer_details.acquirer_merchant_id),+ updated_by: storage_scheme.to_string(),},},Err(error) => authentication::AuthenticationUpdate::ErrorUpdate {@@ -335,6 +341,7 @@ pub async fn update_trackers<F: Clone, Req>(.map(|reason| format!("message: {}, reason: {}", error.message, reason)).or(Some(error.message)),error_code: Some(error.code),+ updated_by: storage_scheme.to_string(),},};state@@ -344,6 +351,7 @@ pub async fn update_trackers<F: Clone, Req>(authentication_update,merchant_key_store,&key_manager_state,+ storage_scheme,).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -464,6 +472,8 @@ pub async fn create_new_authentication(merchant_country_code: None,processor_merchant_id: Some(processor.get_account().get_id().clone()),created_by: initiator.and_then(|initiator| initiator.to_created_by()),+ // Seed with the configured scheme; the insert layer overwrites with the decided one.+ updated_by: Some(processor.get_account().storage_scheme.to_string()),};state@@ -472,6 +482,7 @@ pub async fn create_new_authentication(&key_manager_state,processor.get_key_store(),new_authentication,+ processor.get_account().storage_scheme,).await.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex dd5b10552e..1ac32eb803 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -5057,7 +5057,6 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {.authentication_id.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("missing authentication_id in payment_attempt")?;-// Fetching merchant_connector_account to check if pull_mechanism is enabled for 3ds connectorlet authentication_merchant_connector_account = helpers::get_merchant_connector_account(@@ -5097,6 +5096,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {&authentication_id,platform.get_processor().get_key_store(),key_manager_state,+ platform.get_processor().get_account().storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {@@ -12821,6 +12821,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(.attach_printable("missing authentication_id in payment_attempt")?,platform.get_processor().get_key_store(),key_manager_state,+ storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)@@ -12855,6 +12856,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(payment_intent.payment_id,payment_intent.force_3ds_challenge_trigger.unwrap_or(false),platform.get_processor().get_key_store(),+ storage_scheme,)).await?};diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 26fc6c2e4f..28f7c6fee6 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -2116,7 +2116,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forpayment_data.payment_attempt.profile_id.clone(),payment_data.payment_attempt.organization_id.clone(),)- );+ )+ .update_storage_scheme(platform.get_processor().get_account().storage_scheme);let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {cavv: None,@@ -2183,7 +2184,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forsync_response.clone(),payment_data.payment_attempt.organization_id.clone(),)- );+ )+ .update_storage_scheme(platform.get_processor().get_account().storage_scheme);let cryptogram = sync_response.authentication_details.and_then(|authentication_details| authentication_details.three_ds_data.and_then(|data| data.authentication_cryptogram)).ok_or(errors::ApiErrorResponse::MissingRequiredField{field_name:"authentication_cryptogram"})?;diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex 9a610f12a1..c3ec3ed75e 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -2877,6 +2877,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(Some(mut authentication_store) => {let authentication_update = hyperswitch_domain_models::authentication::AuthenticationUpdate::PostAuthorizationUpdate {authentication_lifecycle_status: enums::AuthenticationLifecycleStatus::Used,+ updated_by: processor.get_account().storage_scheme.to_string(),};let updated_authentication = state.store@@ -2885,6 +2886,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(authentication_update,processor.get_key_store(),&key_manager_state,+ processor.get_account().storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;@@ -2893,7 +2895,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(}None => None,};- };+ }let amount_captured = get_total_amount_captured(&router_data.request,diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rsindex 73ee0e5bec..905daf853b 100644--- a/crates/router/src/core/payments/operations/payment_status.rs+++ b/crates/router/src/core/payments/operations/payment_status.rs@@ -485,6 +485,7 @@ async fn get_tracker_for_sync<authentication_id,platform.get_processor().get_key_store(),key_manager_state,+ platform.get_processor().get_account().storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rsindex d770700d2e..224ecfa943 100644--- a/crates/router/src/core/unified_authentication_service.rs+++ b/crates/router/src/core/unified_authentication_service.rs@@ -686,6 +686,8 @@ pub async fn create_new_authentication(merchant_country_code: None,processor_merchant_id: Some(processor.get_account().get_id().clone()),created_by: initiator.and_then(|initiator| initiator.to_created_by()),+ // Seed with the configured scheme; the insert layer overwrites with the decided one.+ updated_by: Some(processor.get_account().storage_scheme.to_string()),};state@@ -694,6 +696,7 @@ pub async fn create_new_authentication(&key_manager_state,processor.get_key_store(),new_authentication,+ processor.get_account().storage_scheme,).await.to_duplicate_response(ApiErrorResponse::GenericDuplicateError {@@ -1052,6 +1055,7 @@ pub async fn authentication_eligibility_core(&authentication_id,platform.get_processor().get_key_store(),&key_manager_state,+ merchant_account.storage_scheme,).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {@@ -1203,9 +1207,11 @@ pub async fn authentication_eligibility_core(acquirer_bin: acquirer_details.as_ref().and_then(|d| d.acquirer_bin.clone()),acquirer_merchant_id: acquirer_details.as_ref().and_then(|d| d.acquirer_assigned_merchant_id.clone()),acquirer_country_code: acquirer_details.as_ref().and_then(|d| d.acquirer_country_code.clone()),+ updated_by: merchant_account.storage_scheme.to_string(),},platform.get_processor().get_key_store(),key_manager_state_ref,+ merchant_account.storage_scheme,).await.change_context(ApiErrorResponse::InternalServerError)@@ -1318,6 +1324,7 @@ pub async fn authentication_eligibility_core(None,merchant_category_code,merchant_country_code.clone(),+ merchant_account.storage_scheme,)).await?;@@ -1359,6 +1366,7 @@ pub async fn authentication_authenticate_core(&authentication_id,platform.get_processor().get_key_store(),&key_manager_state,+ merchant_account.storage_scheme,).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {@@ -1467,6 +1475,7 @@ pub async fn authentication_authenticate_core(.and_then(|sdk_information| sdk_information.device_details),None,None,+ merchant_account.storage_scheme,)).await?;@@ -1691,6 +1700,7 @@ pub async fn authentication_eligibility_check_core(&authentication_id,platform.get_processor().get_key_store(),&key_manager_state,+ merchant_account.storage_scheme,).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {@@ -1975,6 +1985,7 @@ async fn execute_post_authentication_flow(None,None,None,+ merchant_account.storage_scheme,).await?;@@ -2070,6 +2081,7 @@ pub async fn authentication_sync_core(&authentication_id,platform.get_processor().get_key_store(),&key_manager_state,+ merchant_account.storage_scheme,).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {@@ -2384,6 +2396,7 @@ pub async fn authentication_post_sync_core(&authentication_id,platform.get_processor().get_key_store(),&key_manager_state,+ merchant_account.storage_scheme,).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {@@ -2440,6 +2453,7 @@ pub async fn authentication_post_sync_core(None,None,None,+ merchant_account.storage_scheme,).await?;@@ -2508,6 +2522,7 @@ pub async fn authentication_session_core(&authentication_id,platform.get_processor().get_key_store(),&key_manager_state,+ merchant_account.storage_scheme,).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {diff --git a/crates/router/src/core/unified_authentication_service/utils.rs b/crates/router/src/core/unified_authentication_service/utils.rsindex 7520efff90..d7254071bf 100644--- a/crates/router/src/core/unified_authentication_service/utils.rs+++ b/crates/router/src/core/unified_authentication_service/utils.rs@@ -171,6 +171,7 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(device_details: Option<api_models::payments::DeviceDetails>,merchant_category_code: Option<common_enums::MerchantCategoryCode>,merchant_country_code: Option<common_types::payments::MerchantCountryCode>,+ storage_scheme: diesel_models::enums::MerchantStorageScheme,) -> RouterResult<hyperswitch_domain_models::authentication::Authentication> {let key_state = state.into();let authentication_update = match router_data.response {@@ -308,6 +309,7 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(shipping_country: shipping_address.clone().and_then(|shipping| shipping.address.clone().and_then(|address| address.country.map(|country| country.to_string()))),+ updated_by: storage_scheme.to_string(),},)}@@ -373,6 +375,7 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(device_display: device_details.as_ref().and_then(|details| details.device_display.clone()),+ updated_by: storage_scheme.to_string(),},)}@@ -411,6 +414,7 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(eci: authentication_details.eci,challenge_cancel: authentication_details.challenge_cancel,challenge_code_reason: authentication_details.challenge_code_reason,+ updated_by: storage_scheme.to_string(),},)}@@ -433,6 +437,7 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(.map(|reason| format!("message: {}, reason: {}", error.message, reason)).or(Some(error.message)),error_code: Some(error.code),+ updated_by: storage_scheme.to_string(),},),}?;@@ -444,6 +449,7 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(authentication_update,merchant_key_store,&key_state,+ storage_scheme,).await.change_context(ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex 229bb63714..ebd51e3199 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -1873,6 +1873,7 @@ async fn external_authentication_incoming_webhook_flow(eci: authentication_details.eci,challenge_cancel: authentication_details.challenge_cancel,challenge_code_reason: authentication_details.challenge_code_reason,+ updated_by: platform.get_processor().get_account().storage_scheme.to_string(),};let authentication =if let webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) =@@ -1886,6 +1887,7 @@ async fn external_authentication_incoming_webhook_flow(&authentication_id,platform.get_processor().get_key_store(),&key_manager_state,+ platform.get_processor().get_account().storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {@@ -1901,6 +1903,7 @@ async fn external_authentication_incoming_webhook_flow(connector_authentication_id.clone(),platform.get_processor().get_key_store(),&key_manager_state,+ platform.get_processor().get_account().storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {@@ -1920,6 +1923,7 @@ async fn external_authentication_incoming_webhook_flow(authentication_update,platform.get_processor().get_key_store(),&key_manager_state,+ platform.get_processor().get_account().storage_scheme,).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex a1a6cdc24e..64253ae414 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -55,6 +55,7 @@ use hyperswitch_domain_models::payouts::{payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,};use hyperswitch_domain_models::{+ authentication::AuthenticationInterface,card_issuer::CardIssuersInterface,cards_info::CardsInfoInterface,master_key::MasterKeyInterface,@@ -143,7 +144,7 @@ pub trait StorageInterface:+ health_check::HealthCheckDbInterface+ user_authentication_method::UserAuthenticationMethodInterface+ hyperswitch_ai_interaction::HyperswitchAiInteractionInterface- + authentication::AuthenticationInterface+ + AuthenticationInterface<Error = StorageError>+ generic_link::GenericLinkInterface+ relay::RelayInterface+ user::theme::ThemeInterfacediff --git a/crates/router/src/db/authentication.rs b/crates/router/src/db/authentication.rsindex 35a1f5f810..a40be88d5b 100644--- a/crates/router/src/db/authentication.rs+++ b/crates/router/src/db/authentication.rs@@ -1,519 +1 @@-use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState};-use error_stack::{report, ResultExt};-use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;-use router_env::{instrument, tracing};-use storage_impl::{- behaviour::{Conversion, ForeignInto, ReverseConversion},- StorageError,-};--use super::{MockDb, Store};-use crate::{connection, core::errors::CustomResult, types::storage};--#[async_trait::async_trait]-pub trait AuthenticationInterface {- async fn insert_authentication(- &self,- state: &KeyManagerState,- merchant_key_store: &MerchantKeyStore,- authentication: hyperswitch_domain_models::authentication::Authentication,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError>;-- async fn find_authentication_by_merchant_id_authentication_id(- &self,- merchant_id: &common_utils::id_type::MerchantId,- authentication_id: &common_utils::id_type::AuthenticationId,- merchant_key_store: &MerchantKeyStore,- state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError>;-- async fn find_authentication_by_merchant_id_connector_authentication_id(- &self,- merchant_id: common_utils::id_type::MerchantId,- connector_authentication_id: String,- merchant_key_store: &MerchantKeyStore,- state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError>;-- async fn update_authentication_by_merchant_id_authentication_id(- &self,- previous_state: hyperswitch_domain_models::authentication::Authentication,- authentication_update: hyperswitch_domain_models::authentication::AuthenticationUpdate,- merchant_key_store: &MerchantKeyStore,- state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError>;-}--#[async_trait::async_trait]-impl AuthenticationInterface for Store {- #[instrument(skip_all)]- async fn insert_authentication(- &self,- state: &KeyManagerState,- merchant_key_store: &MerchantKeyStore,- authentication: hyperswitch_domain_models::authentication::Authentication,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {- let conn = connection::pg_connection_write(self).await?;-- authentication- .construct_new()- .await- .change_context(StorageError::EncryptionError)?- .insert(&conn)- .await- .map_err(|error| report!(StorageError::from(error)))?- .convert(- state,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(StorageError::DecryptionError)- }-- #[instrument(skip_all)]- async fn find_authentication_by_merchant_id_authentication_id(- &self,- merchant_id: &common_utils::id_type::MerchantId,- authentication_id: &common_utils::id_type::AuthenticationId,- merchant_key_store: &MerchantKeyStore,- state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {- let conn = connection::pg_connection_read(self).await?;- storage::Authentication::find_by_merchant_id_authentication_id(- &conn,- merchant_id,- authentication_id,- )- .await- .map_err(|error| report!(StorageError::from(error)))- .async_and_then(|authn| async {- authn- .convert(- state,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(StorageError::DecryptionError)- })- .await- }-- #[instrument(skip_all)]- async fn find_authentication_by_merchant_id_connector_authentication_id(- &self,- merchant_id: common_utils::id_type::MerchantId,- connector_authentication_id: String,- merchant_key_store: &MerchantKeyStore,- state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {- let conn = connection::pg_connection_read(self).await?;- storage::Authentication::find_authentication_by_merchant_id_connector_authentication_id(- &conn,- &merchant_id,- &connector_authentication_id,- )- .await- .map_err(|error| report!(StorageError::from(error)))- .async_and_then(|authn| async {- authn- .convert(- state,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(StorageError::DecryptionError)- })- .await- }-- #[instrument(skip_all)]- async fn update_authentication_by_merchant_id_authentication_id(- &self,- previous_state: hyperswitch_domain_models::authentication::Authentication,- authentication_update: hyperswitch_domain_models::authentication::AuthenticationUpdate,- merchant_key_store: &MerchantKeyStore,- state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {- let conn = connection::pg_connection_write(self).await?;- storage::Authentication::update_by_merchant_id_authentication_id(- &conn,- previous_state.merchant_id,- previous_state.authentication_id,- authentication_update.foreign_into(),- )- .await- .map_err(|error| report!(StorageError::from(error)))- .async_and_then(|authn| async {- authn- .convert(- state,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(StorageError::DecryptionError)- })- .await- }-}--#[async_trait::async_trait]-impl AuthenticationInterface for MockDb {- async fn insert_authentication(- &self,- state: &KeyManagerState,- merchant_key_store: &MerchantKeyStore,- authentication: hyperswitch_domain_models::authentication::Authentication,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {- let mut authentications = self.authentications.lock().await;- if authentications.iter().any(|authentication_inner| {- authentication_inner.authentication_id == authentication.authentication_id- }) {- Err(StorageError::DuplicateValue {- entity: "authentication_id",- key: Some(- authentication- .authentication_id- .get_string_repr()- .to_string(),- ),- })?- }- let authentication_new = storage::Authentication {- created_at: common_utils::date_time::now(),- modified_at: common_utils::date_time::now(),- authentication_id: authentication.authentication_id,- merchant_id: authentication.merchant_id,- authentication_status: authentication.authentication_status,- authentication_connector: authentication.authentication_connector,- connector_authentication_id: authentication.connector_authentication_id,- authentication_data: None,- payment_method_id: authentication.payment_method_id,- authentication_type: authentication.authentication_type,- authentication_lifecycle_status: authentication.authentication_lifecycle_status,- error_code: authentication.error_code,- error_message: authentication.error_message,- connector_metadata: authentication.connector_metadata,- maximum_supported_version: authentication.maximum_supported_version,- threeds_server_transaction_id: authentication.threeds_server_transaction_id,- cavv: authentication.cavv,- authentication_flow_type: authentication.authentication_flow_type,- message_version: authentication.message_version,- eci: authentication.eci,- trans_status: authentication.trans_status,- acquirer_bin: authentication.acquirer_bin,- acquirer_merchant_id: authentication.acquirer_merchant_id,- three_ds_method_data: authentication.three_ds_method_data,- three_ds_method_url: authentication.three_ds_method_url,- acs_url: authentication.acs_url,- challenge_request: authentication.challenge_request,- challenge_request_key: authentication.challenge_request_key,- acs_reference_number: authentication.acs_reference_number,- acs_trans_id: authentication.acs_trans_id,- acs_signed_content: authentication.acs_signed_content,- profile_id: authentication.profile_id,- payment_id: authentication.payment_id,- merchant_connector_id: authentication.merchant_connector_id,- ds_trans_id: authentication.ds_trans_id,- directory_server_id: authentication.directory_server_id,- acquirer_country_code: authentication.acquirer_country_code,- service_details: authentication.service_details,- organization_id: authentication.organization_id,- authentication_client_secret: authentication.authentication_client_secret,- force_3ds_challenge: authentication.force_3ds_challenge,- psd2_sca_exemption_type: authentication.psd2_sca_exemption_type,- return_url: authentication.return_url,- amount: authentication.amount,- currency: authentication.currency,- billing_address: None,- shipping_address: None,- browser_info: authentication.browser_info,- email: None,- profile_acquirer_id: authentication.profile_acquirer_id,- challenge_code: authentication.challenge_code,- challenge_cancel: authentication.challenge_cancel,- challenge_code_reason: authentication.challenge_code_reason,- message_extension: authentication.message_extension,- customer_details: authentication.customer_details,- earliest_supported_version: authentication.earliest_supported_version,- latest_supported_version: authentication.latest_supported_version,- mcc: authentication.mcc,- platform: authentication.platform.map(|platform| platform.to_string()),- device_type: authentication.device_type,- device_brand: authentication.device_brand,- device_os: authentication.device_os,- device_display: authentication.device_display,- browser_name: authentication.browser_name,- browser_version: authentication.browser_version,- scheme_name: authentication.scheme_name,- exemption_requested: authentication.exemption_requested,- exemption_accepted: authentication.exemption_accepted,- issuer_id: authentication.issuer_id,- issuer_country: authentication.issuer_country,- merchant_country_code: authentication.merchant_country_code,- billing_country: authentication.billing_country,- shipping_country: authentication.shipping_country,- processor_merchant_id: authentication.processor_merchant_id,- created_by: authentication- .created_by- .map(|created_by| created_by.to_string()),- };-- let authentication: hyperswitch_domain_models::authentication::Authentication =- authentication_new- .convert(- state,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(StorageError::EncryptionError)?;-- authentications.push(authentication.clone());- Ok(authentication)- }-- async fn find_authentication_by_merchant_id_authentication_id(- &self,- merchant_id: &common_utils::id_type::MerchantId,- authentication_id: &common_utils::id_type::AuthenticationId,- _merchant_key_store: &MerchantKeyStore,- _state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {- let authentications = self.authentications.lock().await;-- authentications- .iter()- .find(|auth| {- auth.merchant_id == *merchant_id && auth.authentication_id == *authentication_id- })- .cloned()- .ok_or(- StorageError::ValueNotFound(format!(- "Authentication not found for merchant_id: {} and authentication_id: {}",- merchant_id.get_string_repr(),- authentication_id.get_string_repr()- ))- .into(),- )- }-- async fn find_authentication_by_merchant_id_connector_authentication_id(- &self,- merchant_id: common_utils::id_type::MerchantId,- connector_authentication_id: String,- _merchant_key_store: &MerchantKeyStore,- _state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {- let authentications = self.authentications.lock().await;-- authentications- .iter()- .find(|auth| {- auth.merchant_id == merchant_id- && auth.connector_authentication_id.as_ref()- == Some(&connector_authentication_id)- })- .cloned()- .ok_or(- StorageError::ValueNotFound(format!(- "Authentication not found for merchant_id: {} and connector_authentication_id: {}",- merchant_id.get_string_repr(),- connector_authentication_id- ))- .into(),- )- }-- async fn update_authentication_by_merchant_id_authentication_id(- &self,- previous_state: hyperswitch_domain_models::authentication::Authentication,- authentication_update: hyperswitch_domain_models::authentication::AuthenticationUpdate,- _merchant_key_store: &MerchantKeyStore,- _state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {- let mut authentications = self.authentications.lock().await;-- let auth_to_update = authentications- .iter_mut()- .find(|auth| {- auth.merchant_id == previous_state.merchant_id- && auth.authentication_id == previous_state.authentication_id- })- .ok_or(StorageError::ValueNotFound(format!(- "Authentication not found for merchant_id: {} and authentication_id: {}",- previous_state.merchant_id.get_string_repr(),- previous_state.authentication_id.get_string_repr()- )))?;-- // Apply the update based on the variant- match authentication_update {- hyperswitch_domain_models::authentication::AuthenticationUpdate::PreAuthenticationVersionCallUpdate {- maximum_supported_3ds_version,- message_version,- } => {- auth_to_update.maximum_supported_version = Some(maximum_supported_3ds_version);- auth_to_update.message_version = Some(message_version);- }- hyperswitch_domain_models::authentication::AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {- threeds_server_transaction_id,- three_ds_method_data,- three_ds_method_url,- acquirer_bin,- acquirer_merchant_id,- connector_metadata,- } => {- auth_to_update.threeds_server_transaction_id = Some(threeds_server_transaction_id);- auth_to_update.three_ds_method_data = three_ds_method_data;- auth_to_update.three_ds_method_url = three_ds_method_url;- auth_to_update.acquirer_bin = acquirer_bin;- auth_to_update.acquirer_merchant_id = acquirer_merchant_id;- auth_to_update.connector_metadata = connector_metadata;- }- hyperswitch_domain_models::authentication::AuthenticationUpdate::PreAuthenticationUpdate {- threeds_server_transaction_id,- maximum_supported_3ds_version,- connector_authentication_id,- three_ds_method_data,- three_ds_method_url,- message_version,- connector_metadata,- authentication_status,- acquirer_bin,- acquirer_merchant_id,- directory_server_id,- acquirer_country_code,- billing_address,- shipping_address,- browser_info,- email,- scheme_id,- merchant_category_code,- merchant_country_code,- billing_country,- shipping_country,- earliest_supported_version,- latest_supported_version,- } => {- auth_to_update.threeds_server_transaction_id = Some(threeds_server_transaction_id);- auth_to_update.maximum_supported_version = Some(maximum_supported_3ds_version);- auth_to_update.connector_authentication_id = Some(connector_authentication_id);- auth_to_update.three_ds_method_data = three_ds_method_data;- auth_to_update.three_ds_method_url = three_ds_method_url;- auth_to_update.message_version = Some(message_version);- auth_to_update.connector_metadata = connector_metadata;- auth_to_update.authentication_status = authentication_status;- auth_to_update.acquirer_bin = acquirer_bin;- auth_to_update.acquirer_merchant_id = acquirer_merchant_id;- auth_to_update.directory_server_id = directory_server_id;- auth_to_update.acquirer_country_code = acquirer_country_code;- auth_to_update.billing_address = *billing_address;- auth_to_update.shipping_address = *shipping_address;- auth_to_update.browser_info = *browser_info;- auth_to_update.email = email;- auth_to_update.scheme_name = scheme_id;- auth_to_update.mcc = merchant_category_code;- auth_to_update.merchant_country_code = merchant_country_code;- auth_to_update.billing_country = billing_country;- auth_to_update.shipping_country = shipping_country;- auth_to_update.earliest_supported_version = earliest_supported_version;- auth_to_update.latest_supported_version = latest_supported_version;- }- hyperswitch_domain_models::authentication::AuthenticationUpdate::AuthenticationUpdate {- trans_status,- authentication_type,- acs_url,- challenge_request,- acs_reference_number,- acs_trans_id,- acs_signed_content,- connector_metadata,- authentication_status,- ds_trans_id,- eci,- challenge_code,- challenge_cancel,- challenge_code_reason,- message_extension,- challenge_request_key,- device_type,- device_brand,- device_os,- device_display,- } => {- auth_to_update.trans_status = Some(trans_status);- auth_to_update.authentication_type = Some(authentication_type);- auth_to_update.acs_url = acs_url;- auth_to_update.challenge_request = challenge_request;- auth_to_update.acs_reference_number = acs_reference_number;- auth_to_update.acs_trans_id = acs_trans_id;- auth_to_update.acs_signed_content = acs_signed_content;- auth_to_update.connector_metadata = connector_metadata;- auth_to_update.authentication_status = authentication_status;- auth_to_update.ds_trans_id = ds_trans_id;- auth_to_update.eci = eci;- auth_to_update.challenge_code = challenge_code;- auth_to_update.challenge_cancel = challenge_cancel;- auth_to_update.challenge_code_reason = challenge_code_reason;- auth_to_update.message_extension = message_extension;- auth_to_update.challenge_request_key = challenge_request_key;- auth_to_update.device_type = device_type;- auth_to_update.device_brand = device_brand;- auth_to_update.device_os = device_os;- auth_to_update.device_display = device_display;- }- hyperswitch_domain_models::authentication::AuthenticationUpdate::PostAuthenticationUpdate {- trans_status,- eci,- authentication_status,- challenge_cancel,- challenge_code_reason,- } => {- auth_to_update.trans_status = Some(trans_status);- auth_to_update.eci = eci;- auth_to_update.authentication_status = authentication_status;- auth_to_update.challenge_cancel = challenge_cancel;- auth_to_update.challenge_code_reason = challenge_code_reason;- }- hyperswitch_domain_models::authentication::AuthenticationUpdate::ErrorUpdate {- error_message,- error_code,- authentication_status,- connector_authentication_id,- } => {- auth_to_update.error_message = error_message;- auth_to_update.error_code = error_code;- auth_to_update.authentication_status = authentication_status;- auth_to_update.connector_authentication_id = connector_authentication_id;- }- hyperswitch_domain_models::authentication::AuthenticationUpdate::PostAuthorizationUpdate {- authentication_lifecycle_status,- } => {- auth_to_update.authentication_lifecycle_status = authentication_lifecycle_status;- }- hyperswitch_domain_models::authentication::AuthenticationUpdate::AuthenticationStatusUpdate {- trans_status,- authentication_status,- } => {- auth_to_update.trans_status = Some(trans_status);- auth_to_update.authentication_status = authentication_status;- }- hyperswitch_domain_models::authentication::AuthenticationUpdate::AcquirerDetailsUpdate {- acquirer_bin,- acquirer_merchant_id,- acquirer_country_code,- } => {- auth_to_update.acquirer_bin = acquirer_bin;- auth_to_update.acquirer_merchant_id = acquirer_merchant_id;- auth_to_update.acquirer_country_code = acquirer_country_code;- }- }-- auth_to_update.modified_at = common_utils::date_time::now();-- Ok(auth_to_update.clone())- }-}+pub use hyperswitch_domain_models::authentication::AuthenticationInterface;diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex cad17bbb58..d10617e28d 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -24,6 +24,7 @@ use hyperswitch_domain_models::payouts::{#[cfg(feature = "v2")]use hyperswitch_domain_models::platform::Initiator;use hyperswitch_domain_models::{+ authentication::AuthenticationInterface,cards_info::CardsInfoInterface,disputes,invoice::{Invoice as DomainInvoice, InvoiceInterface, InvoiceUpdate as DomainInvoiceUpdate},@@ -66,7 +67,6 @@ use crate::{self,address::AddressInterface,api_keys::ApiKeyInterface,- authentication::AuthenticationInterface,authorization::AuthorizationInterface,business_profile::ProfileInterface,callback_mapper::CallbackMapperInterface,@@ -4105,16 +4105,21 @@ impl AuthorizationInterface for KafkaStore {#[async_trait::async_trait]impl AuthenticationInterface for KafkaStore {+ type Error = errors::StorageError;+async fn insert_authentication(&self,state: &KeyManagerState,key_store: &domain::MerchantKeyStore,authentication: hyperswitch_domain_models::authentication::Authentication,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, errors::StorageError>- {+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<+ hyperswitch_domain_models::authentication::Authentication,+ errors::StorageError,+ > {let auth = self.diesel_store- .insert_authentication(state, key_store, authentication)+ .insert_authentication(state, key_store, authentication, storage_scheme).await?;if let Err(er) = self@@ -4134,14 +4139,18 @@ impl AuthenticationInterface for KafkaStore {authentication_id: &id_type::AuthenticationId,key_store: &domain::MerchantKeyStore,state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, errors::StorageError>- {+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<+ hyperswitch_domain_models::authentication::Authentication,+ errors::StorageError,+ > {self.diesel_store.find_authentication_by_merchant_id_authentication_id(merchant_id,authentication_id,key_store,state,+ storage_scheme,).await}@@ -4152,14 +4161,18 @@ impl AuthenticationInterface for KafkaStore {connector_authentication_id: String,key_store: &domain::MerchantKeyStore,state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, errors::StorageError>- {+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<+ hyperswitch_domain_models::authentication::Authentication,+ errors::StorageError,+ > {self.diesel_store.find_authentication_by_merchant_id_connector_authentication_id(merchant_id,connector_authentication_id,key_store,state,+ storage_scheme,).await}@@ -4170,8 +4183,11 @@ impl AuthenticationInterface for KafkaStore {authentication_update: hyperswitch_domain_models::authentication::AuthenticationUpdate,key_store: &domain::MerchantKeyStore,state: &KeyManagerState,- ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, errors::StorageError>- {+ storage_scheme: MerchantStorageScheme,+ ) -> error_stack::Result<+ hyperswitch_domain_models::authentication::Authentication,+ errors::StorageError,+ > {let auth = self.diesel_store.update_authentication_by_merchant_id_authentication_id(@@ -4179,6 +4195,7 @@ impl AuthenticationInterface for KafkaStore {authentication_update,key_store,state,+ storage_scheme,).await?;diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex b5536c8b85..06567bef36 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -328,6 +328,7 @@ pub async fn find_mca_from_authentication_id_type(&authentication_id,platform.get_processor().get_key_store(),&state.into(),+ platform.get_processor().get_account().storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?,@@ -337,6 +338,7 @@ pub async fn find_mca_from_authentication_id_type(connector_authentication_id,platform.get_processor().get_key_store(),&state.into(),+ platform.get_processor().get_account().storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?diff --git a/crates/storage_impl/src/authentication.rs b/crates/storage_impl/src/authentication.rsindex d28ed572ed..65d6731f3b 100644--- a/crates/storage_impl/src/authentication.rs+++ b/crates/storage_impl/src/authentication.rs@@ -1,490 +1,744 @@-use std::str::FromStr;--use async_trait::async_trait;use common_utils::{- encryption::Encryption,- errors::{CustomResult, ValidationError},- pii,- types::keymanager::{Identifier, KeyManagerState, ToEncryptable},+ errors::CustomResult,+ ext_traits::{AsyncExt, Encode},+ fallback_reverse_lookup_not_found,+};+use diesel_models::{+ authentication::Authentication as diesel_authentication, reverse_lookup::ReverseLookupNew,};use error_stack::ResultExt;use hyperswitch_domain_models::{- authentication::{- AuthenticationUpdate, EncryptedAuthentication, FromRequestEncryptableAuthentication,- },- type_encryption::{crypto_operation, AsyncLift, CryptoOperation},+ authentication::{Authentication, AuthenticationInterface, AuthenticationUpdate},+ behaviour::Conversion,+ merchant_key_store::MerchantKeyStore,};-use hyperswitch_masking::{PeekInterface, Secret};--use crate::behaviour::{self, ForeignFrom};--#[async_trait]-impl behaviour::Conversion for hyperswitch_domain_models::authentication::Authentication {- type DstType = diesel_models::authentication::Authentication;- type NewDstType = diesel_models::authentication::AuthenticationNew;-- async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {- Ok(Self::DstType {- authentication_id: self.authentication_id,- merchant_id: self.merchant_id,- authentication_connector: self.authentication_connector,- connector_authentication_id: self.connector_authentication_id,- authentication_data: self.authentication_data,- payment_method_id: self.payment_method_id,- authentication_type: self.authentication_type,- authentication_status: self.authentication_status,- authentication_lifecycle_status: self.authentication_lifecycle_status,- created_at: self.created_at,- modified_at: self.modified_at,- error_message: self.error_message,- error_code: self.error_code,- connector_metadata: self.connector_metadata,- maximum_supported_version: self.maximum_supported_version,- threeds_server_transaction_id: self.threeds_server_transaction_id,- cavv: self.cavv,- authentication_flow_type: self.authentication_flow_type,- message_version: self.message_version,- eci: self.eci,- trans_status: self.trans_status,- acquirer_bin: self.acquirer_bin,- acquirer_merchant_id: self.acquirer_merchant_id,- three_ds_method_data: self.three_ds_method_data,- three_ds_method_url: self.three_ds_method_url,- acs_url: self.acs_url,- challenge_request: self.challenge_request,- acs_reference_number: self.acs_reference_number,- acs_trans_id: self.acs_trans_id,- acs_signed_content: self.acs_signed_content,- profile_id: self.profile_id,- payment_id: self.payment_id,- merchant_connector_id: self.merchant_connector_id,- ds_trans_id: self.ds_trans_id,- directory_server_id: self.directory_server_id,- acquirer_country_code: self.acquirer_country_code,- service_details: self.service_details,- organization_id: self.organization_id,- authentication_client_secret: self.authentication_client_secret,- force_3ds_challenge: self.force_3ds_challenge,- psd2_sca_exemption_type: self.psd2_sca_exemption_type,- return_url: self.return_url,- amount: self.amount,- currency: self.currency,- billing_address: self.billing_address.map(Encryption::from),- shipping_address: self.shipping_address.map(Encryption::from),- browser_info: self.browser_info,- email: self.email.map(|email| email.into()),- profile_acquirer_id: self.profile_acquirer_id,- challenge_code: self.challenge_code,- challenge_cancel: self.challenge_cancel,- challenge_code_reason: self.challenge_code_reason,- message_extension: self.message_extension,- challenge_request_key: self.challenge_request_key,- customer_details: self.customer_details,- earliest_supported_version: self.earliest_supported_version,- latest_supported_version: self.latest_supported_version,- mcc: self.mcc,- platform: self.platform.map(|platform| platform.to_string()),- device_type: self.device_type,- device_brand: self.device_brand,- device_os: self.device_os,- device_display: self.device_display,- browser_name: self.browser_name,- browser_version: self.browser_version,- scheme_name: self.scheme_name,- exemption_requested: self.exemption_requested,- exemption_accepted: self.exemption_accepted,- issuer_id: self.issuer_id,- issuer_country: self.issuer_country,- merchant_country_code: self.merchant_country_code,- billing_country: self.billing_country,- shipping_country: self.shipping_country,- processor_merchant_id: self.processor_merchant_id,- created_by: self.created_by.map(|created_by| created_by.to_string()),- })- }+use redis_interface::HsetnxReply;+use router_env::{instrument, tracing};++use crate::{+ diesel_error_to_data_error,+ errors::{self, RedisErrorExt},+ kv_router_store::KVRouterStore,+ lookup::ReverseLookupInterface,+ mock_db::MockDb,+ redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},+ utils::{pg_connection_read, pg_connection_write, try_redis_get_else_try_database_get},+ DatabaseStore, RouterStore,+};++impl crate::redis::kv_store::KvStorePartition for diesel_authentication {}++/// Insert the connector-authentication-id reverse lookup (webhook find path).+#[inline]+#[instrument(skip_all)]+async fn add_connector_authentication_id_to_reverse_lookup<T: DatabaseStore>(+ store: &KVRouterStore<T>,+ key: &str,+ field: &str,+ merchant_id: &common_utils::id_type::MerchantId,+ connector_authentication_id: &str,+ storage_scheme: common_enums::MerchantStorageScheme,+) -> error_stack::Result<diesel_models::reverse_lookup::ReverseLookup, errors::StorageError> {+ let reverse_lookup = ReverseLookupNew {+ lookup_id: diesel_authentication::get_connector_authentication_lookup_id(+ merchant_id,+ connector_authentication_id,+ ),+ pk_id: key.to_owned(),+ sk_id: field.to_owned(),+ source: "authentication".to_string(),+ updated_by: storage_scheme.to_string(),+ };+ store+ .insert_reverse_lookup(reverse_lookup, storage_scheme)+ .await+}- async fn convert_back(- state: &KeyManagerState,- other: Self::DstType,- key: &Secret<Vec<u8>>,- _key_manager_identifier: Identifier,- ) -> CustomResult<Self, ValidationError> {- let encrypted_data = crypto_operation(+#[async_trait::async_trait]+impl<T: DatabaseStore> AuthenticationInterface for RouterStore<T> {+ type Error = errors::StorageError;++ #[instrument(skip_all)]+ async fn insert_authentication(+ &self,+ state: &common_utils::types::keymanager::KeyManagerState,+ merchant_key_store: &MerchantKeyStore,+ authentication: Authentication,+ _storage_scheme: common_enums::MerchantStorageScheme,+ ) -> error_stack::Result<Authentication, errors::StorageError> {+ let conn = pg_connection_write(self).await?;+ let inserted_authentication = authentication+ .construct_new()+ .await+ .change_context(errors::StorageError::EncryptionError)?+ .insert(&conn)+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })?;+ Authentication::convert_back(state,- common_utils::type_name!(Self),- CryptoOperation::BatchDecrypt(EncryptedAuthentication::to_encryptable(- EncryptedAuthentication {- billing_address: other.billing_address.clone(),- shipping_address: other.shipping_address.clone(),- },- )),- Identifier::Merchant(other.merchant_id.clone()),- key.peek(),+ inserted_authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),).await- .and_then(|val| val.try_into_batchoperation())- .change_context(ValidationError::InvalidValue {- message: "Failed while decrypting authentication data".to_string(),- })?;-- let decrypted_data = FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)- .change_context(ValidationError::InvalidValue {- message: "Failed while decrypting authentication data".to_string(),- })?;+ .change_context(errors::StorageError::DecryptionError)+ }- let email_decrypted = other- .clone()- .async_lift(|inner| async {- crypto_operation::<String, pii::EmailStrategy>(- state,- common_utils::type_name!(Self),- CryptoOperation::DecryptOptional(inner),- Identifier::Merchant(other.merchant_id.clone()),- key.peek(),- )- .await- .and_then(|val| val.try_into_optionaloperation())- })+ #[instrument(skip_all)]+ async fn find_authentication_by_merchant_id_authentication_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ authentication_id: &common_utils::id_type::AuthenticationId,+ merchant_key_store: &MerchantKeyStore,+ state: &common_utils::types::keymanager::KeyManagerState,+ _storage_scheme: common_enums::MerchantStorageScheme,+ ) -> error_stack::Result<Authentication, errors::StorageError> {+ let conn = pg_connection_read(self).await?;+ diesel_authentication::find_by_merchant_id_authentication_id(+ &conn,+ merchant_id,+ authentication_id,+ )+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })+ .async_and_then(|authentication| async {+ Authentication::convert_back(+ state,+ authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ ).await- .change_context(ValidationError::InvalidValue {- message: "Failed while decrypting authentication email".to_string(),- })?;+ .change_context(errors::StorageError::DecryptionError)+ })+ .await+ }- Ok(Self {- authentication_id: other.authentication_id,- merchant_id: other.merchant_id,- authentication_connector: other.authentication_connector,- connector_authentication_id: other.connector_authentication_id,- authentication_data: other.authentication_data,- payment_method_id: other.payment_method_id,- authentication_type: other.authentication_type,- authentication_status: other.authentication_status,- authentication_lifecycle_status: other.authentication_lifecycle_status,- created_at: other.created_at,- modified_at: other.modified_at,- error_message: other.error_message,- error_code: other.error_code,- connector_metadata: other.connector_metadata,- maximum_supported_version: other.maximum_supported_version,- threeds_server_transaction_id: other.threeds_server_transaction_id,- cavv: other.cavv,- authentication_flow_type: other.authentication_flow_type,- message_version: other.message_version,- eci: other.eci,- trans_status: other.trans_status,- acquirer_bin: other.acquirer_bin,- acquirer_merchant_id: other.acquirer_merchant_id,- three_ds_method_data: other.three_ds_method_data,- three_ds_method_url: other.three_ds_method_url,- acs_url: other.acs_url,- challenge_request: other.challenge_request,- acs_reference_number: other.acs_reference_number,- acs_trans_id: other.acs_trans_id,- acs_signed_content: other.acs_signed_content,- profile_id: other.profile_id,- payment_id: other.payment_id,- merchant_connector_id: other.merchant_connector_id,- ds_trans_id: other.ds_trans_id,- directory_server_id: other.directory_server_id,- acquirer_country_code: other.acquirer_country_code,- organization_id: other.organization_id,- mcc: other.mcc,- amount: other.amount,- currency: other.currency,- issuer_country: other.issuer_country,- earliest_supported_version: other.earliest_supported_version,- latest_supported_version: other.latest_supported_version,- platform: other- .platform- .as_deref()- .map(|s| {- api_models::payments::DeviceChannel::from_str(s).change_context(- ValidationError::InvalidValue {- message: "Invalid device channel".into(),- },- )- })- .transpose()?,- device_type: other.device_type,- device_brand: other.device_brand,- device_os: other.device_os,- device_display: other.device_display,- browser_name: other.browser_name,- browser_version: other.browser_version,- issuer_id: other.issuer_id,- scheme_name: other.scheme_name,- exemption_requested: other.exemption_requested,- exemption_accepted: other.exemption_accepted,- service_details: other.service_details,- authentication_client_secret: other.authentication_client_secret,- force_3ds_challenge: other.force_3ds_challenge,- psd2_sca_exemption_type: other.psd2_sca_exemption_type,- return_url: other.return_url,- billing_address: decrypted_data.billing_address,- shipping_address: decrypted_data.shipping_address,- browser_info: other.browser_info,- email: email_decrypted,- profile_acquirer_id: other.profile_acquirer_id,- challenge_code: other.challenge_code,- challenge_cancel: other.challenge_cancel,- challenge_code_reason: other.challenge_code_reason,- message_extension: other.message_extension,- challenge_request_key: other.challenge_request_key,- customer_details: other.customer_details,- billing_country: other.billing_country,- shipping_country: other.shipping_country,- merchant_country_code: other.merchant_country_code,- processor_merchant_id: other.processor_merchant_id,- created_by: other- .created_by- .and_then(|created_by| created_by.parse::<common_utils::types::CreatedBy>().ok()),+ #[instrument(skip_all)]+ async fn find_authentication_by_merchant_id_connector_authentication_id(+ &self,+ merchant_id: common_utils::id_type::MerchantId,+ connector_authentication_id: String,+ merchant_key_store: &MerchantKeyStore,+ state: &common_utils::types::keymanager::KeyManagerState,+ _storage_scheme: common_enums::MerchantStorageScheme,+ ) -> error_stack::Result<Authentication, errors::StorageError> {+ let conn = pg_connection_read(self).await?;+ diesel_authentication::find_authentication_by_merchant_id_connector_authentication_id(+ &conn,+ &merchant_id,+ &connector_authentication_id,+ )+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })+ .async_and_then(|authentication| async {+ Authentication::convert_back(+ state,+ authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)})+ .await}- async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {- Ok(Self::NewDstType {- authentication_id: self.authentication_id,- merchant_id: self.merchant_id,- authentication_connector: self.authentication_connector,- connector_authentication_id: self.connector_authentication_id,- authentication_data: self.authentication_data,- payment_method_id: self.payment_method_id,- authentication_type: self.authentication_type,- authentication_status: self.authentication_status,- authentication_lifecycle_status: self.authentication_lifecycle_status,- error_message: self.error_message,- error_code: self.error_code,- connector_metadata: self.connector_metadata,- maximum_supported_version: self.maximum_supported_version,- threeds_server_transaction_id: self.threeds_server_transaction_id,- cavv: self.cavv,- authentication_flow_type: self.authentication_flow_type,- message_version: self.message_version,- eci: self.eci,- trans_status: self.trans_status,- acquirer_bin: self.acquirer_bin,- acquirer_merchant_id: self.acquirer_merchant_id,- three_ds_method_data: self.three_ds_method_data,- three_ds_method_url: self.three_ds_method_url,- acs_url: self.acs_url,- challenge_request: self.challenge_request,- acs_reference_number: self.acs_reference_number,- acs_trans_id: self.acs_trans_id,- acs_signed_content: self.acs_signed_content,- profile_id: self.profile_id,- payment_id: self.payment_id,- merchant_connector_id: self.merchant_connector_id,- ds_trans_id: self.ds_trans_id,- directory_server_id: self.directory_server_id,- acquirer_country_code: self.acquirer_country_code,- service_details: self.service_details,- organization_id: self.organization_id,- authentication_client_secret: self.authentication_client_secret,- force_3ds_challenge: self.force_3ds_challenge,- psd2_sca_exemption_type: self.psd2_sca_exemption_type,- return_url: self.return_url,- amount: self.amount,- currency: self.currency,- billing_address: self.billing_address.map(Encryption::from),- shipping_address: self.shipping_address.map(Encryption::from),- browser_info: self.browser_info,- email: self.email.map(|email| email.into()),- profile_acquirer_id: self.profile_acquirer_id,- challenge_code: self.challenge_code,- challenge_cancel: self.challenge_cancel,- challenge_code_reason: self.challenge_code_reason,- message_extension: self.message_extension,- challenge_request_key: self.challenge_request_key,- customer_details: self.customer_details,- earliest_supported_version: self.earliest_supported_version,- latest_supported_version: self.latest_supported_version,- mcc: self.mcc,- platform: self.platform.map(|platform| platform.to_string()),- device_type: self.device_type,- device_brand: self.device_brand,- device_os: self.device_os,- device_display: self.device_display,- browser_name: self.browser_name,- browser_version: self.browser_version,- scheme_name: self.scheme_name,- exemption_requested: self.exemption_requested,- exemption_accepted: self.exemption_accepted,- issuer_id: self.issuer_id,- issuer_country: self.issuer_country,- merchant_country_code: self.merchant_country_code,- created_at: self.created_at,- modified_at: self.modified_at,- billing_country: self.billing_country,- shipping_country: self.shipping_country,- processor_merchant_id: self.processor_merchant_id,- created_by: self.created_by.map(|created_by| created_by.to_string()),+ #[instrument(skip_all)]+ async fn update_authentication_by_merchant_id_authentication_id(+ &self,+ previous_state: Authentication,+ authentication_update: AuthenticationUpdate,+ merchant_key_store: &MerchantKeyStore,+ state: &common_utils::types::keymanager::KeyManagerState,+ _storage_scheme: common_enums::MerchantStorageScheme,+ ) -> error_stack::Result<Authentication, errors::StorageError> {+ let conn = pg_connection_write(self).await?;+ diesel_authentication::update_by_merchant_id_authentication_id(+ &conn,+ &previous_state.merchant_id,+ &previous_state.authentication_id,+ diesel_models::authentication::AuthenticationUpdateInternal::from(+ diesel_models::authentication::AuthenticationUpdate::from(authentication_update),+ ),+ )+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)})+ .async_and_then(|authentication| async {+ Authentication::convert_back(+ state,+ authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ })+ .await}}-impl ForeignFrom<AuthenticationUpdate> for diesel_models::authentication::AuthenticationUpdate {- fn foreign_from(authentication_update: AuthenticationUpdate) -> Self {- match authentication_update {- AuthenticationUpdate::PreAuthenticationVersionCallUpdate {- maximum_supported_3ds_version,- message_version,- } => Self::PreAuthenticationVersionCallUpdate {- maximum_supported_3ds_version,- message_version,- },- AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {- threeds_server_transaction_id,- three_ds_method_data,- three_ds_method_url,- acquirer_bin,- acquirer_merchant_id,- connector_metadata,- } => Self::PreAuthenticationThreeDsMethodCall {- threeds_server_transaction_id,- three_ds_method_data,- three_ds_method_url,- acquirer_bin,- acquirer_merchant_id,- connector_metadata,- },- AuthenticationUpdate::PreAuthenticationUpdate {- threeds_server_transaction_id,- maximum_supported_3ds_version,- connector_authentication_id,- three_ds_method_data,- three_ds_method_url,- message_version,- connector_metadata,- authentication_status,- acquirer_bin,- acquirer_merchant_id,- directory_server_id,- acquirer_country_code,- billing_address,- shipping_address,- browser_info,- email,- scheme_id,- merchant_category_code,- merchant_country_code,- billing_country,- shipping_country,- earliest_supported_version,- latest_supported_version,- } => Self::PreAuthenticationUpdate {- threeds_server_transaction_id,- maximum_supported_3ds_version,- connector_authentication_id,- three_ds_method_data,- three_ds_method_url,- message_version,- connector_metadata,- authentication_status,- acquirer_bin,- acquirer_merchant_id,- directory_server_id,- acquirer_country_code,- billing_address: billing_address.map(|billing_address| billing_address.into()),- shipping_address: shipping_address.map(|shipping_address| shipping_address.into()),- browser_info,- email: email.map(|email| email.into()),- scheme_id,- merchant_category_code,- merchant_country_code,- billing_country,- shipping_country,- earliest_supported_version,- latest_supported_version,- },- AuthenticationUpdate::AuthenticationUpdate {- trans_status,- authentication_type,- acs_url,- challenge_request,- acs_reference_number,- acs_trans_id,- acs_signed_content,- connector_metadata,- authentication_status,- ds_trans_id,- eci,- challenge_code,- challenge_cancel,- challenge_code_reason,- message_extension,- challenge_request_key,- device_type,- device_brand,- device_os,- device_display,- } => Self::AuthenticationUpdate {- trans_status,- authentication_type,- acs_url,- challenge_request,- acs_reference_number,- acs_trans_id,- acs_signed_content,- connector_metadata,- authentication_status,- ds_trans_id,- eci,- challenge_code,- challenge_cancel,- challenge_code_reason,- message_extension,- challenge_request_key,- device_type,- device_brand,- device_os,- device_display,- },- AuthenticationUpdate::PostAuthenticationUpdate {- trans_status,- eci,- authentication_status,- challenge_cancel,- challenge_code_reason,- } => Self::PostAuthenticationUpdate {- trans_status,- eci,- authentication_status,- challenge_cancel,- challenge_code_reason,- },- AuthenticationUpdate::ErrorUpdate {- error_message,- error_code,- authentication_status,- connector_authentication_id,- } => Self::ErrorUpdate {- error_message,- error_code,- authentication_status,- connector_authentication_id,- },- AuthenticationUpdate::PostAuthorizationUpdate {- authentication_lifecycle_status,- } => Self::PostAuthorizationUpdate {- authentication_lifecycle_status,- },- AuthenticationUpdate::AuthenticationStatusUpdate {- trans_status,- authentication_status,- } => Self::AuthenticationStatusUpdate {- trans_status,- authentication_status,+#[async_trait::async_trait]+impl<T: DatabaseStore> AuthenticationInterface for KVRouterStore<T> {+ type Error = errors::StorageError;++ #[instrument(skip_all)]+ async fn insert_authentication(+ &self,+ state: &common_utils::types::keymanager::KeyManagerState,+ merchant_key_store: &MerchantKeyStore,+ authentication: Authentication,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> error_stack::Result<Authentication, errors::StorageError> {+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_authentication>(+ self,+ storage_scheme,+ Op::Insert,+ ))+ .await;++ match storage_scheme {+ common_enums::MerchantStorageScheme::PostgresOnly => {+ self.router_store+ .insert_authentication(+ state,+ merchant_key_store,+ authentication,+ storage_scheme,+ )+ .await+ }+ common_enums::MerchantStorageScheme::RedisKv => {+ // Record which layer wrote this row; drives KV-vs-Postgres routing on later updates.+ let authentication = authentication.update_storage_scheme(storage_scheme);++ let merchant_id = &authentication.merchant_id;+ let authentication_id = &authentication.authentication_id;+ let payment_id = &authentication.payment_id;++ // Co-locate on the payment's partition; modular auth is its own partition.+ let key = match payment_id {+ Some(payment_id) => PartitionKey::MerchantIdPaymentId {+ merchant_id,+ payment_id,+ },+ None => PartitionKey::AuthenticationId { authentication_id },+ };+ let field = diesel_authentication::get_hash_key_for_kv_store(authentication_id);+ let key_str = key.to_string();++ let authentication_to_insert = authentication+ .clone()+ .construct_new()+ .await+ .change_context(errors::StorageError::EncryptionError)?;++ let mut query_gen_conn = pg_connection_write(self).await?;+ let drainer_query = authentication_to_insert+ .generate_drainer_insert_query(&mut query_gen_conn)+ .await+ .change_context(errors::StorageError::KVError)+ .attach_printable("Failed to generate authentication insert query")?;++ let diesel_authentication =+ <Authentication as Conversion>::convert(authentication.clone())+ .await+ .change_context(errors::StorageError::EncryptionError)?;++ // Reverse lookup by authentication id (find when under the payment's partition).+ let authentication_id_lookup = ReverseLookupNew {+ lookup_id: diesel_authentication::get_authentication_id_lookup_id(+ merchant_id,+ authentication_id,+ ),+ pk_id: key_str.clone(),+ sk_id: field.clone(),+ source: "authentication".to_string(),+ updated_by: storage_scheme.to_string(),+ };+ self.insert_reverse_lookup(authentication_id_lookup, storage_scheme)+ .await?;++ // Reverse lookup by connector authentication id (webhook path), when present.+ if let Some(connector_authentication_id) =+ authentication.connector_authentication_id.as_ref()+ {+ add_connector_authentication_id_to_reverse_lookup(+ self,+ &key_str,+ &field,+ merchant_id,+ connector_authentication_id,+ storage_scheme,+ )+ .await?;+ }++ match Box::pin(kv_wrapper::<diesel_authentication, _, _>(+ self,+ KvOperation::<diesel_authentication>::HSetNx(+ &field,+ &diesel_authentication,+ drainer_query,+ ),+ key,+ ))+ .await+ .map_err(|err| err.to_redis_failed_response(&key_str))?+ .try_into_hsetnx()+ {+ Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {+ entity: "authentication",+ key: Some(key_str),+ }+ .into()),+ Ok(HsetnxReply::KeySet) => Ok(authentication),+ Err(error) => Err(error.change_context(errors::StorageError::KVError)),+ }+ }+ }+ }++ #[instrument(skip_all)]+ async fn find_authentication_by_merchant_id_authentication_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ authentication_id: &common_utils::id_type::AuthenticationId,+ merchant_key_store: &MerchantKeyStore,+ state: &common_utils::types::keymanager::KeyManagerState,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> error_stack::Result<Authentication, errors::StorageError> {+ let database_call = || async {+ let conn = pg_connection_read(self).await?;+ diesel_authentication::find_by_merchant_id_authentication_id(+ &conn,+ merchant_id,+ authentication_id,+ )+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })+ };++ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_authentication>(+ self,+ storage_scheme,+ Op::Find,+ ))+ .await;++ let diesel_authentication = match storage_scheme {+ common_enums::MerchantStorageScheme::PostgresOnly => database_call().await,+ common_enums::MerchantStorageScheme::RedisKv => {+ // Resolve partition/field via the authentication-id reverse lookup.+ let lookup_id = diesel_authentication::get_authentication_id_lookup_id(+ merchant_id,+ authentication_id,+ );+ let lookup = fallback_reverse_lookup_not_found!(+ self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)+ .await,+ {+ let diesel_authentication = database_call().await?;+ Authentication::convert_back(+ state,+ diesel_authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ }+ );+ let key = PartitionKey::CombinationKey {+ combination: &lookup.pk_id,+ };+ Box::pin(try_redis_get_else_try_database_get(+ async {+ Box::pin(kv_wrapper::<diesel_authentication, _, _>(+ self,+ KvOperation::<diesel_authentication>::HGet(&lookup.sk_id),+ key,+ ))+ .await?+ .try_into_hget()+ },+ database_call,+ ))+ .await+ }+ }?;++ Authentication::convert_back(+ state,+ diesel_authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ }++ #[instrument(skip_all)]+ async fn find_authentication_by_merchant_id_connector_authentication_id(+ &self,+ merchant_id: common_utils::id_type::MerchantId,+ connector_authentication_id: String,+ merchant_key_store: &MerchantKeyStore,+ state: &common_utils::types::keymanager::KeyManagerState,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> error_stack::Result<Authentication, errors::StorageError> {+ let database_call = || async {+ let conn = pg_connection_read(self).await?;+ diesel_authentication::find_authentication_by_merchant_id_connector_authentication_id(+ &conn,+ &merchant_id,+ &connector_authentication_id,+ )+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })+ };++ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_authentication>(+ self,+ storage_scheme,+ Op::Find,+ ))+ .await;++ let diesel_authentication = match storage_scheme {+ common_enums::MerchantStorageScheme::PostgresOnly => database_call().await,+ common_enums::MerchantStorageScheme::RedisKv => {+ // Resolve partition/field via the connector reverse lookup (webhook flow).+ let lookup_id = diesel_authentication::get_connector_authentication_lookup_id(+ &merchant_id,+ &connector_authentication_id,+ );+ let lookup = fallback_reverse_lookup_not_found!(+ self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)+ .await,+ {+ let diesel_authentication = database_call().await?;+ Authentication::convert_back(+ state,+ diesel_authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ }+ );+ let key = PartitionKey::CombinationKey {+ combination: &lookup.pk_id,+ };+ Box::pin(try_redis_get_else_try_database_get(+ async {+ Box::pin(kv_wrapper::<diesel_authentication, _, _>(+ self,+ KvOperation::<diesel_authentication>::HGet(&lookup.sk_id),+ key,+ ))+ .await?+ .try_into_hget()+ },+ database_call,+ ))+ .await+ }+ }?;++ Authentication::convert_back(+ state,+ diesel_authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ }++ #[instrument(skip_all)]+ async fn update_authentication_by_merchant_id_authentication_id(+ &self,+ previous_state: Authentication,+ authentication_update: AuthenticationUpdate,+ merchant_key_store: &MerchantKeyStore,+ state: &common_utils::types::keymanager::KeyManagerState,+ storage_scheme: common_enums::MerchantStorageScheme,+ ) -> error_stack::Result<Authentication, errors::StorageError> {+ let merchant_id = previous_state.merchant_id.clone();+ let authentication_id = previous_state.authentication_id.clone();+ let payment_id = previous_state.payment_id.clone();++ // Same partition key as on insert (payment's, else authentication's own).+ let key = match payment_id {+ Some(ref payment_id) => PartitionKey::MerchantIdPaymentId {+ merchant_id: &merchant_id,+ payment_id,},- AuthenticationUpdate::AcquirerDetailsUpdate {- acquirer_bin,- acquirer_merchant_id,- acquirer_country_code,- } => Self::AcquirerDetailsUpdate {- acquirer_bin,- acquirer_merchant_id,- acquirer_country_code,+ None => PartitionKey::AuthenticationId {+ authentication_id: &authentication_id,},+ };+ let field = diesel_authentication::get_hash_key_for_kv_store(&authentication_id);++ // The previous write location drives KV-vs-Postgres routing in decide_storage_scheme.+ let updated_by = previous_state.updated_by.clone();+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_authentication>(+ self,+ storage_scheme,+ Op::Update(key.clone(), &field, updated_by.as_deref()),+ ))+ .await;++ match storage_scheme {+ common_enums::MerchantStorageScheme::PostgresOnly => {+ self.router_store+ .update_authentication_by_merchant_id_authentication_id(+ previous_state,+ authentication_update,+ merchant_key_store,+ state,+ storage_scheme,+ )+ .await+ }+ common_enums::MerchantStorageScheme::RedisKv => {+ let key_str = key.to_string();++ let current_authentication =+ <Authentication as Conversion>::convert(previous_state.clone())+ .await+ .change_context(errors::StorageError::EncryptionError)?;++ // Captured before the changeset to detect a connector-authentication-id change.+ let old_connector_authentication_id =+ previous_state.connector_authentication_id.clone();++ let authentication_update_internal =+ diesel_models::authentication::AuthenticationUpdateInternal::from(+ diesel_models::authentication::AuthenticationUpdate::from(+ authentication_update,+ ),+ );++ let updated_authentication = authentication_update_internal+ .clone()+ .apply_changeset(current_authentication);++ // Add the connector reverse lookup when the update sets/changes that id.+ match (+ old_connector_authentication_id,+ &updated_authentication.connector_authentication_id,+ ) {+ (None, Some(connector_authentication_id)) => {+ add_connector_authentication_id_to_reverse_lookup(+ self,+ &key_str,+ &field,+ &merchant_id,+ connector_authentication_id,+ storage_scheme,+ )+ .await?;+ }+ (Some(old), Some(connector_authentication_id))+ if &old != connector_authentication_id =>+ {+ add_connector_authentication_id_to_reverse_lookup(+ self,+ &key_str,+ &field,+ &merchant_id,+ connector_authentication_id,+ storage_scheme,+ )+ .await?;+ }+ (_, _) => {}+ }++ let redis_value = updated_authentication+ .encode_to_string_of_json()+ .change_context(errors::StorageError::SerializationFailed)?;++ let mut query_gen_conn = pg_connection_write(self).await?;+ let drainer_query = authentication_update_internal+ .generate_drainer_update_query(+ &mut query_gen_conn,+ merchant_id.clone(),+ authentication_id.clone(),+ )+ .await+ .change_context(errors::StorageError::KVError)+ .attach_printable("Failed to generate authentication update query")?;++ Box::pin(kv_wrapper::<(), _, _>(+ self,+ KvOperation::<diesel_authentication>::Hset(+ (&field, redis_value),+ drainer_query,+ ),+ key,+ ))+ .await+ .map_err(|err| err.to_redis_failed_response(&key_str))?+ .try_into_hset()+ .change_context(errors::StorageError::KVError)?;++ Authentication::convert_back(+ state,+ updated_authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ }}}}++#[async_trait::async_trait]+impl AuthenticationInterface for MockDb {+ type Error = errors::StorageError;++ async fn insert_authentication(+ &self,+ _state: &common_utils::types::keymanager::KeyManagerState,+ _merchant_key_store: &MerchantKeyStore,+ authentication: Authentication,+ _storage_scheme: common_enums::MerchantStorageScheme,+ ) -> CustomResult<Authentication, errors::StorageError> {+ let mut authentications = self.authentications.lock().await;+ if authentications.iter().any(|authentication_inner| {+ authentication_inner.authentication_id == authentication.authentication_id+ }) {+ Err(errors::StorageError::DuplicateValue {+ entity: "authentication_id",+ key: Some(+ authentication+ .authentication_id+ .get_string_repr()+ .to_string(),+ ),+ })?+ }+ authentications.push(authentication.clone());+ Ok(authentication)+ }++ async fn find_authentication_by_merchant_id_authentication_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ authentication_id: &common_utils::id_type::AuthenticationId,+ _merchant_key_store: &MerchantKeyStore,+ _state: &common_utils::types::keymanager::KeyManagerState,+ _storage_scheme: common_enums::MerchantStorageScheme,+ ) -> CustomResult<Authentication, errors::StorageError> {+ let authentications = self.authentications.lock().await;+ authentications+ .iter()+ .find(|auth| {+ auth.merchant_id == *merchant_id && auth.authentication_id == *authentication_id+ })+ .cloned()+ .ok_or(+ errors::StorageError::ValueNotFound(format!(+ "Authentication not found for merchant_id: {} and authentication_id: {}",+ merchant_id.get_string_repr(),+ authentication_id.get_string_repr()+ ))+ .into(),+ )+ }++ async fn find_authentication_by_merchant_id_connector_authentication_id(+ &self,+ merchant_id: common_utils::id_type::MerchantId,+ connector_authentication_id: String,+ _merchant_key_store: &MerchantKeyStore,+ _state: &common_utils::types::keymanager::KeyManagerState,+ _storage_scheme: common_enums::MerchantStorageScheme,+ ) -> CustomResult<Authentication, errors::StorageError> {+ let authentications = self.authentications.lock().await;+ authentications+ .iter()+ .find(|auth| {+ auth.merchant_id == merchant_id+ && auth.connector_authentication_id.as_ref()+ == Some(&connector_authentication_id)+ })+ .cloned()+ .ok_or(+ errors::StorageError::ValueNotFound(format!(+ "Authentication not found for merchant_id: {} and connector_authentication_id: {}",+ merchant_id.get_string_repr(),+ connector_authentication_id+ ))+ .into(),+ )+ }++ async fn update_authentication_by_merchant_id_authentication_id(+ &self,+ previous_state: Authentication,+ authentication_update: AuthenticationUpdate,+ merchant_key_store: &MerchantKeyStore,+ state: &common_utils::types::keymanager::KeyManagerState,+ _storage_scheme: common_enums::MerchantStorageScheme,+ ) -> CustomResult<Authentication, errors::StorageError> {+ let mut authentications = self.authentications.lock().await;+ let item = authentications+ .iter_mut()+ .find(|auth| {+ auth.merchant_id == previous_state.merchant_id+ && auth.authentication_id == previous_state.authentication_id+ })+ .ok_or(errors::StorageError::ValueNotFound(format!(+ "Authentication not found for merchant_id: {} and authentication_id: {}",+ previous_state.merchant_id.get_string_repr(),+ previous_state.authentication_id.get_string_repr()+ )))?;++ let current_authentication =+ <Authentication as Conversion>::convert(previous_state.clone())+ .await+ .change_context(errors::StorageError::EncryptionError)?;++ let updated_authentication =+ diesel_models::authentication::AuthenticationUpdateInternal::from(+ diesel_models::authentication::AuthenticationUpdate::from(authentication_update),+ )+ .apply_changeset(current_authentication);++ *item = Authentication::convert_back(+ state,+ updated_authentication,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)?;++ Ok(item.clone())+ }+}diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rsindex 919dbe608d..87b9d280bb 100644--- a/crates/storage_impl/src/lib.rs+++ b/crates/storage_impl/src/lib.rs@@ -560,6 +560,19 @@ impl UniqueConstraints for diesel_models::Mandate {}}+impl UniqueConstraints for diesel_models::authentication::Authentication {+ fn unique_constraints(&self) -> Vec<String> {+ // Mirror the DB's only uniqueness: the `authentication_id` primary key.+ vec![format!(+ "authentication_{}",+ self.authentication_id.get_string_repr()+ )]+ }+ fn table_name(&self) -> &str {+ "Authentication"+ }+}+#[cfg(feature = "v1")]impl UniqueConstraints for diesel_models::Customer {fn unique_constraints(&self) -> Vec<String> {diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rsindex e20ca31b99..d51dc3f38d 100644--- a/crates/storage_impl/src/redis/kv_store.rs+++ b/crates/storage_impl/src/redis/kv_store.rs@@ -46,6 +46,9 @@ pub enum PartitionKey<'a> {merchant_id: &'a common_utils::id_type::MerchantId,mandate_id: &'a str,},+ AuthenticationId {+ authentication_id: &'a common_utils::id_type::AuthenticationId,+ },#[cfg(feature = "v2")]GlobalId {id: &'a str,@@ -99,6 +102,9 @@ impl std::fmt::Display for PartitionKey<'_> {"mid_{}_mandate_{mandate_id}",merchant_id.get_string_repr())),+ PartitionKey::AuthenticationId { authentication_id } => {+ f.write_str(authentication_id.get_string_repr())+ }#[cfg(feature = "v2")]PartitionKey::GlobalId { id } => f.write_str(&format!("global_cust_{id}")),diff --git a/migrations/2026-06-16-110031-0000_add_updated_by_for_authentication/down.sql b/migrations/2026-06-16-110031-0000_add_updated_by_for_authentication/down.sqlnew file mode 100644index 0000000000..5064d27ad0--- /dev/null+++ b/migrations/2026-06-16-110031-0000_add_updated_by_for_authentication/down.sql@@ -0,0 +1,2 @@+-- This file should undo anything in `up.sql`+ALTER TABLE authentication DROP COLUMN updated_by;diff --git a/migrations/2026-06-16-110031-0000_add_updated_by_for_authentication/up.sql b/migrations/2026-06-16-110031-0000_add_updated_by_for_authentication/up.sqlnew file mode 100644index 0000000000..6248cf9132--- /dev/null+++ b/migrations/2026-06-16-110031-0000_add_updated_by_for_authentication/up.sql@@ -0,0 +1,2 @@+-- Your SQL goes here+ALTER TABLE authentication ADD COLUMN updated_by VARCHAR(32);