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): add domain models for authentication and support kafka filters in dashboard (#10446)
Sahkal Poddar3900793df437
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 89d05ab443..243769c61f 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -17317,6 +17317,32 @@"BRW"]},+ "DeviceDetails": {+ "type": "object",+ "description": "Device details for collecting Device information",+ "properties": {+ "device_type": {+ "type": "string",+ "description": "Device type",+ "nullable": true+ },+ "device_brand": {+ "type": "string",+ "description": "Device brand",+ "nullable": true+ },+ "device_os": {+ "type": "string",+ "description": "Device OS",+ "nullable": true+ },+ "device_display": {+ "type": "string",+ "description": "Device display",+ "nullable": true+ }+ }+ },"DisplayAmountOnSdk": {"type": "object","required": [@@ -28813,6 +28839,11 @@"type": "string","description": "Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred","nullable": true+ },+ "error_message": {+ "type": "string",+ "description": "Error message if any",+ "nullable": true}}},@@ -35777,6 +35808,14 @@}],"nullable": true+ },+ "device_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/DeviceDetails"+ }+ ],+ "nullable": true}}},diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 63db4c58b7..9c20779516 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -11063,6 +11063,32 @@"BRW"]},+ "DeviceDetails": {+ "type": "object",+ "description": "Device details for collecting Device information",+ "properties": {+ "device_type": {+ "type": "string",+ "description": "Device type",+ "nullable": true+ },+ "device_brand": {+ "type": "string",+ "description": "Device brand",+ "nullable": true+ },+ "device_os": {+ "type": "string",+ "description": "Device OS",+ "nullable": true+ },+ "device_display": {+ "type": "string",+ "description": "Device display",+ "nullable": true+ }+ }+ },"DisplayAmountOnSdk": {"type": "object","required": [@@ -20729,6 +20755,11 @@"type": "string","description": "Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred","nullable": true+ },+ "error_message": {+ "type": "string",+ "description": "Error message if any",+ "nullable": true}}},@@ -25958,6 +25989,14 @@}],"nullable": true+ },+ "device_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/DeviceDetails"+ }+ ],+ "nullable": true}}},diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 5bb1fb0212..c4258f94e4 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -10825,10 +10825,23 @@ pub enum ThreeDsCompletionIndicator {}/// Device Channel indicating whether request is coming from App or Browser-#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)]+#[derive(+ Debug,+ serde::Serialize,+ serde::Deserialize,+ Clone,+ ToSchema,+ Eq,+ PartialEq,+ Display,+ strum::EnumString,+)]+#[strum(serialize_all = "UPPERCASE")]pub enum DeviceChannel {+ #[strum(serialize = "APP")]#[serde(rename = "APP")]App,+ #[strum(serialize = "BRW")]#[serde(rename = "BRW")]Browser,}@@ -10850,6 +10863,21 @@ pub struct SdkInformation {pub sdk_max_timeout: u8,/// Indicates the type of 3DS SDKpub sdk_type: Option<SdkType>,+ /// Device details for collecting Device information+ pub device_details: Option<DeviceDetails>,+}++/// Device details for collecting Device information+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]+pub struct DeviceDetails {+ /// Device type+ pub device_type: Option<String>,+ /// Device brand+ pub device_brand: Option<String>,+ /// Device OS+ pub device_os: Option<String>,+ /// Device display+ pub device_display: Option<String>,}/// Enum representing the type of 3DS SDK.@@ -10968,6 +10996,8 @@ pub struct PaymentsExternalAuthenticationResponse {pub three_ds_requestor_url: String,/// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurredpub three_ds_requestor_app_url: Option<String>,+ /// Error message if any+ pub error_message: Option<String>,}#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 7757c0b313..00886a7398 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -3165,7 +3165,7 @@ pub enum DisputeStatus {DisputeLost,}-#[derive(Debug, Clone, AsExpression, PartialEq, ToSchema)]+#[derive(Debug, Clone, AsExpression, PartialEq, ToSchema, Eq)]#[schema(value_type = String,title = "4 digit Merchant category code (MCC)",diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rsindex f0f84650fb..a539d874e2 100644--- a/crates/diesel_models/src/authentication.rs+++ b/crates/diesel_models/src/authentication.rs@@ -1,12 +1,5 @@-use std::str::FromStr;--use common_utils::{- encryption::Encryption,- errors::{CustomResult, ValidationError},- pii,-};+use common_utils::{encryption::Encryption, pii};use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};-use error_stack::ResultExt;use serde::{self, Deserialize, Serialize};use crate::schema::authentication;@@ -73,30 +66,24 @@ pub struct Authentication {pub message_extension: Option<pii::SecretSerdeValue>,pub challenge_request_key: Option<String>,pub customer_details: Option<Encryption>,-}--impl Authentication {- pub fn is_separate_authn_required(&self) -> bool {- self.maximum_supported_version- .as_ref()- .is_some_and(|version| version.get_major() == 2)- }-- // get authentication_connector from authentication record and check if it is jwt flow- pub fn is_jwt_flow(&self) -> CustomResult<bool, ValidationError> {- Ok(self- .authentication_connector- .clone()- .map(|connector| {- common_enums::AuthenticationConnectors::from_str(&connector)- .change_context(ValidationError::InvalidValue {- message: "failed to parse authentication_connector".to_string(),- })- .map(|connector_enum| connector_enum.is_jwt_flow())- })- .transpose()?- .unwrap_or(false))- }+ pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub latest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub mcc: Option<common_enums::MerchantCategoryCode>,+ pub platform: Option<String>,+ pub device_type: Option<String>,+ pub device_brand: Option<String>,+ pub device_os: Option<String>,+ pub device_display: Option<String>,+ pub browser_name: Option<String>,+ pub browser_version: Option<String>,+ pub scheme_name: Option<String>,+ pub exemption_requested: Option<bool>,+ pub exemption_accepted: Option<bool>,+ pub issuer_id: Option<String>,+ pub issuer_country: Option<String>,+ pub merchant_country_code: Option<String>,+ pub billing_country: Option<String>,+ pub shipping_country: Option<String>,}#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Insertable)]@@ -106,7 +93,7 @@ pub struct AuthenticationNew {pub merchant_id: common_utils::id_type::MerchantId,pub authentication_connector: Option<String>,pub connector_authentication_id: Option<String>,- // pub authentication_data: Option<serde_json::Value>,+ pub authentication_data: Option<serde_json::Value>,pub payment_method_id: String,pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,pub authentication_status: common_enums::AuthenticationStatus,@@ -155,6 +142,26 @@ pub struct AuthenticationNew {pub message_extension: Option<pii::SecretSerdeValue>,pub challenge_request_key: Option<String>,pub customer_details: Option<Encryption>,+ pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub latest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub mcc: Option<common_enums::MerchantCategoryCode>,+ pub platform: Option<String>,+ pub device_type: Option<String>,+ pub device_brand: Option<String>,+ pub device_os: Option<String>,+ pub device_display: Option<String>,+ pub browser_name: Option<String>,+ pub browser_version: Option<String>,+ pub scheme_name: Option<String>,+ pub exemption_requested: Option<bool>,+ pub exemption_accepted: Option<bool>,+ pub issuer_id: Option<String>,+ pub issuer_country: Option<String>,+ pub merchant_country_code: Option<String>,+ pub created_at: time::PrimitiveDateTime,+ pub modified_at: time::PrimitiveDateTime,+ pub billing_country: Option<String>,+ pub shipping_country: Option<String>,}#[derive(Debug)]@@ -188,6 +195,13 @@ pub enum AuthenticationUpdate {shipping_address: Option<Encryption>,browser_info: Box<Option<serde_json::Value>>,email: Option<Encryption>,+ scheme_id: Option<String>,+ merchant_category_code: Option<common_enums::MerchantCategoryCode>,+ merchant_country_code: Option<String>,+ billing_country: Option<String>,+ shipping_country: Option<String>,+ earliest_supported_version: Option<common_utils::types::SemanticVersion>,+ latest_supported_version: Option<common_utils::types::SemanticVersion>,},AuthenticationUpdate {trans_status: common_enums::TransactionStatus,@@ -206,6 +220,10 @@ pub enum AuthenticationUpdate {challenge_code_reason: Option<String>,message_extension: Option<pii::SecretSerdeValue>,challenge_request_key: Option<String>,+ device_type: Option<String>,+ device_brand: Option<String>,+ device_os: Option<String>,+ device_display: Option<String>,},PostAuthenticationUpdate {trans_status: common_enums::TransactionStatus,@@ -229,53 +247,6 @@ pub enum AuthenticationUpdate {},}-#[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Serialize, Deserialize)]-#[diesel(table_name = authentication)]-pub struct AuthenticationUpdateInternal {- pub connector_authentication_id: Option<String>,- // pub authentication_data: Option<serde_json::Value>,- pub payment_method_id: Option<String>,- pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,- pub authentication_status: Option<common_enums::AuthenticationStatus>,- pub authentication_lifecycle_status: Option<common_enums::AuthenticationLifecycleStatus>,- pub modified_at: time::PrimitiveDateTime,- pub error_message: Option<String>,- pub error_code: Option<String>,- pub connector_metadata: Option<serde_json::Value>,- pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,- pub threeds_server_transaction_id: Option<String>,- pub authentication_flow_type: Option<String>,- pub message_version: Option<common_utils::types::SemanticVersion>,- pub eci: Option<String>,- pub trans_status: Option<common_enums::TransactionStatus>,- pub acquirer_bin: Option<String>,- pub acquirer_merchant_id: Option<String>,- pub three_ds_method_data: Option<String>,- pub three_ds_method_url: Option<String>,- pub acs_url: Option<String>,- pub challenge_request: Option<String>,- pub acs_reference_number: Option<String>,- pub acs_trans_id: Option<String>,- pub acs_signed_content: Option<String>,- pub ds_trans_id: Option<String>,- pub directory_server_id: Option<String>,- pub acquirer_country_code: Option<String>,- pub service_details: Option<serde_json::Value>,- pub force_3ds_challenge: Option<bool>,- pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,- pub billing_address: Option<Encryption>,- pub shipping_address: Option<Encryption>,- pub browser_info: Option<serde_json::Value>,- pub email: Option<Encryption>,- pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,- pub challenge_code: Option<String>,- pub challenge_cancel: Option<String>,- pub challenge_code_reason: Option<String>,- pub message_extension: Option<pii::SecretSerdeValue>,- pub challenge_request_key: Option<String>,- pub customer_details: Option<Encryption>,-}-impl Default for AuthenticationUpdateInternal {fn default() -> Self {Self {@@ -320,12 +291,95 @@ impl Default for AuthenticationUpdateInternal {message_extension: Default::default(),challenge_request_key: Default::default(),customer_details: Default::default(),+ earliest_supported_version: Default::default(),+ latest_supported_version: Default::default(),+ mcc: Default::default(),+ platform: Default::default(),+ device_type: Default::default(),+ device_brand: Default::default(),+ device_os: Default::default(),+ device_display: Default::default(),+ browser_name: Default::default(),+ browser_version: Default::default(),+ scheme_name: Default::default(),+ exemption_requested: Default::default(),+ exemption_accepted: Default::default(),+ issuer_id: Default::default(),+ issuer_country: Default::default(),+ merchant_country_code: Default::default(),+ billing_country: Default::default(),+ shipping_country: Default::default(),}}}+#[derive(Clone, Debug, Eq, PartialEq, AsChangeset, Serialize, Deserialize)]+#[diesel(table_name = authentication)]+pub struct AuthenticationUpdateInternal {+ pub connector_authentication_id: Option<String>,+ // pub authentication_data: Option<serde_json::Value>,+ pub payment_method_id: Option<String>,+ pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,+ pub authentication_status: Option<common_enums::AuthenticationStatus>,+ pub authentication_lifecycle_status: Option<common_enums::AuthenticationLifecycleStatus>,+ pub modified_at: time::PrimitiveDateTime,+ pub error_message: Option<String>,+ pub error_code: Option<String>,+ pub connector_metadata: Option<serde_json::Value>,+ pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,+ pub threeds_server_transaction_id: Option<String>,+ pub authentication_flow_type: Option<String>,+ pub message_version: Option<common_utils::types::SemanticVersion>,+ pub eci: Option<String>,+ pub trans_status: Option<common_enums::TransactionStatus>,+ pub acquirer_bin: Option<String>,+ pub acquirer_merchant_id: Option<String>,+ pub three_ds_method_data: Option<String>,+ pub three_ds_method_url: Option<String>,+ pub acs_url: Option<String>,+ pub challenge_request: Option<String>,+ pub acs_reference_number: Option<String>,+ pub acs_trans_id: Option<String>,+ pub acs_signed_content: Option<String>,+ pub ds_trans_id: Option<String>,+ pub directory_server_id: Option<String>,+ pub acquirer_country_code: Option<String>,+ pub service_details: Option<serde_json::Value>,+ pub force_3ds_challenge: Option<bool>,+ pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,+ pub billing_address: Option<Encryption>,+ pub shipping_address: Option<Encryption>,+ pub browser_info: Option<serde_json::Value>,+ pub email: Option<Encryption>,+ pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub challenge_code: Option<String>,+ pub challenge_cancel: Option<String>,+ pub challenge_code_reason: Option<String>,+ pub message_extension: Option<pii::SecretSerdeValue>,+ pub challenge_request_key: Option<String>,+ pub customer_details: Option<Encryption>,+ pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub latest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub mcc: Option<common_enums::MerchantCategoryCode>,+ pub platform: Option<String>,+ pub device_type: Option<String>,+ pub device_brand: Option<String>,+ pub device_os: Option<String>,+ pub device_display: Option<String>,+ pub browser_name: Option<String>,+ pub browser_version: Option<String>,+ pub scheme_name: Option<String>,+ pub exemption_requested: Option<bool>,+ pub exemption_accepted: Option<bool>,+ pub issuer_id: Option<String>,+ pub issuer_country: Option<String>,+ pub merchant_country_code: Option<String>,+ pub billing_country: Option<String>,+ pub shipping_country: Option<String>,+}+impl AuthenticationUpdateInternal {- pub fn apply_changeset(self, source: Authentication) -> Authentication {+ pub fn apply_changeset(self, source: AuthenticationNew) -> Authentication {let Self {connector_authentication_id,payment_method_id,@@ -368,6 +422,24 @@ impl AuthenticationUpdateInternal {message_extension,challenge_request_key,customer_details,+ earliest_supported_version,+ latest_supported_version,+ mcc,+ platform,+ device_type,+ device_brand,+ device_os,+ device_display,+ browser_name,+ browser_version,+ scheme_name,+ exemption_requested,+ exemption_accepted,+ issuer_id,+ issuer_country,+ merchant_country_code,+ billing_country,+ shipping_country,} = self;Authentication {connector_authentication_id: connector_authentication_id@@ -415,7 +487,39 @@ impl AuthenticationUpdateInternal {message_extension: message_extension.or(source.message_extension),challenge_request_key: challenge_request_key.or(source.challenge_request_key),customer_details: customer_details.or(source.customer_details),- ..source+ earliest_supported_version: earliest_supported_version+ .or(source.earliest_supported_version),+ latest_supported_version: latest_supported_version.or(source.latest_supported_version),+ mcc: mcc.or(source.mcc),+ platform: platform.or(source.platform),+ device_type: device_type.or(source.device_type),+ device_brand: device_brand.or(source.device_brand),+ device_os: device_os.or(source.device_os),+ device_display: device_display.or(source.device_display),+ browser_name: browser_name.or(source.browser_name),+ browser_version: browser_version.or(source.browser_version),+ scheme_name: scheme_name.or(source.scheme_name),+ exemption_requested: exemption_requested.or(source.exemption_requested),+ exemption_accepted: exemption_accepted.or(source.exemption_accepted),+ issuer_id: issuer_id.or(source.issuer_id),+ issuer_country: issuer_country.or(source.issuer_country),+ merchant_country_code: merchant_country_code.or(source.merchant_country_code),+ authentication_id: source.authentication_id,+ merchant_id: source.merchant_id,+ authentication_connector: source.authentication_connector,+ authentication_data: source.authentication_data,+ created_at: source.created_at,+ cavv: source.cavv,+ profile_id: source.profile_id,+ payment_id: source.payment_id,+ merchant_connector_id: source.merchant_connector_id,+ organization_id: source.organization_id,+ authentication_client_secret: source.authentication_client_secret,+ return_url: source.return_url,+ amount: source.amount,+ currency: source.currency,+ billing_country: billing_country.or(source.billing_country),+ shipping_country: shipping_country.or(source.shipping_country),}}}@@ -472,6 +576,13 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {shipping_address,browser_info,email,+ scheme_id,+ merchant_category_code,+ merchant_country_code,+ billing_country,+ shipping_country,+ earliest_supported_version,+ latest_supported_version,} => Self {threeds_server_transaction_id: Some(threeds_server_transaction_id),maximum_supported_version: Some(maximum_supported_3ds_version),@@ -489,6 +600,13 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {shipping_address,browser_info: *browser_info,email,+ scheme_name: scheme_id,+ mcc: merchant_category_code,+ merchant_country_code,+ billing_country,+ shipping_country,+ earliest_supported_version,+ latest_supported_version,..Default::default()},AuthenticationUpdate::AuthenticationUpdate {@@ -508,6 +626,10 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {challenge_code_reason,message_extension,challenge_request_key,+ device_type,+ device_brand,+ device_os,+ device_display,} => Self {trans_status: Some(trans_status),authentication_type: Some(authentication_type),@@ -525,6 +647,10 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {challenge_code_reason,message_extension,challenge_request_key,+ device_type,+ device_brand,+ device_os,+ device_display,..Default::default()},AuthenticationUpdate::PostAuthenticationUpdate {diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 0e1595b67d..e8489f6580 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -145,6 +145,38 @@ diesel::table! {#[max_length = 255]challenge_request_key -> Nullable<Varchar>,customer_details -> Nullable<Bytea>,+ earliest_supported_version -> Nullable<Jsonb>,+ latest_supported_version -> Nullable<Jsonb>,+ #[max_length = 8]+ mcc -> Nullable<Varchar>,+ #[max_length = 64]+ platform -> Nullable<Varchar>,+ #[max_length = 255]+ device_type -> Nullable<Varchar>,+ #[max_length = 255]+ device_brand -> Nullable<Varchar>,+ #[max_length = 255]+ device_os -> Nullable<Varchar>,+ #[max_length = 255]+ device_display -> Nullable<Varchar>,+ #[max_length = 255]+ browser_name -> Nullable<Varchar>,+ #[max_length = 255]+ browser_version -> Nullable<Varchar>,+ #[max_length = 255]+ scheme_name -> Nullable<Varchar>,+ exemption_requested -> Nullable<Bool>,+ exemption_accepted -> Nullable<Bool>,+ #[max_length = 255]+ issuer_id -> Nullable<Varchar>,+ #[max_length = 16]+ issuer_country -> Nullable<Varchar>,+ #[max_length = 8]+ merchant_country_code -> Nullable<Varchar>,+ #[max_length = 16]+ billing_country -> Nullable<Varchar>,+ #[max_length = 16]+ shipping_country -> Nullable<Varchar>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 1fcad72832..04f001d166 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -145,6 +145,38 @@ diesel::table! {#[max_length = 255]challenge_request_key -> Nullable<Varchar>,customer_details -> Nullable<Bytea>,+ earliest_supported_version -> Nullable<Jsonb>,+ latest_supported_version -> Nullable<Jsonb>,+ #[max_length = 8]+ mcc -> Nullable<Varchar>,+ #[max_length = 64]+ platform -> Nullable<Varchar>,+ #[max_length = 255]+ device_type -> Nullable<Varchar>,+ #[max_length = 255]+ device_brand -> Nullable<Varchar>,+ #[max_length = 255]+ device_os -> Nullable<Varchar>,+ #[max_length = 255]+ device_display -> Nullable<Varchar>,+ #[max_length = 255]+ browser_name -> Nullable<Varchar>,+ #[max_length = 255]+ browser_version -> Nullable<Varchar>,+ #[max_length = 255]+ scheme_name -> Nullable<Varchar>,+ exemption_requested -> Nullable<Bool>,+ exemption_accepted -> Nullable<Bool>,+ #[max_length = 255]+ issuer_id -> Nullable<Varchar>,+ #[max_length = 16]+ issuer_country -> Nullable<Varchar>,+ #[max_length = 8]+ merchant_country_code -> Nullable<Varchar>,+ #[max_length = 16]+ billing_country -> Nullable<Varchar>,+ #[max_length = 16]+ shipping_country -> Nullable<Varchar>,}}diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rsindex c0691c5ffd..b9c627f8fe 100644--- a/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs+++ b/crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs@@ -354,7 +354,7 @@ pub enum ThreeDSRequestorDecoupledRequestIndicator {B,}-#[derive(Debug, Serialize, Deserialize, Clone)]+#[derive(Debug, Serialize, Deserialize, Clone, strum::Display)]pub enum SchemeId {Visa,Mastercard,diff --git a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rsindex e8f1e8ffc6..316957f8c1 100644--- a/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs@@ -101,6 +101,9 @@ impldirectory_server_id: card_range.as_ref().and_then(|card_range| card_range.directory_server_id.clone()),+ scheme_id: card_range+ .as_ref()+ .map(|card_range| card_range.scheme_id.clone().to_string()),})}NetceteraPreAuthenticationResponse::Failure(error_response) => Err(ErrorResponse {diff --git a/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rsindex a6acb3d1e2..ca33b6617a 100644--- a/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs@@ -106,6 +106,7 @@ impl.change_context(errors::ConnectorError::ParsingFailed)?,connector_metadata: Some(connector_metadata),directory_server_id: None,+ scheme_id: pre_authn_response.scheme,})}ThreedsecureioPreAuthenticationResponse::Failure(error_response) => {diff --git a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rsindex 2ee020480e..26b58b7381 100644--- a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs+++ b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs@@ -37,7 +37,6 @@ use hyperswitch_interfaces::{ConnectorValidation,},configs::Connectors,- consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},errors,events::connector_api_logs::ConnectorEvent,types::{self, Response},@@ -144,8 +143,8 @@ impl ConnectorCommon for UnifiedAuthenticationService {Ok(ErrorResponse {status_code: res.status_code,- code: NO_ERROR_CODE.to_owned(),- message: NO_ERROR_MESSAGE.to_owned(),+ code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),+ message: response.error.to_owned(),reason: Some(response.error),attempt_status: None,connector_transaction_id: None,diff --git a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rsindex 5ad58b0908..d7522b1b01 100644--- a/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs@@ -386,7 +386,11 @@ impl<F, T>message_version: maximum_supported_3ds_version,connector_metadata: None,directory_server_id: three_ds_eligibility_response- .and_then(|response| response.directory_server_id),+ .as_ref()+ .and_then(|response| response.directory_server_id.clone()),+ scheme_id: three_ds_eligibility_response+ .as_ref()+ .and_then(|response| response.scheme_id.clone()),},}),..item.datadiff --git a/crates/hyperswitch_domain_models/src/authentication.rs b/crates/hyperswitch_domain_models/src/authentication.rsindex 5ec6f93c14..8b964898c6 100644--- a/crates/hyperswitch_domain_models/src/authentication.rs+++ b/crates/hyperswitch_domain_models/src/authentication.rs@@ -1,12 +1,22 @@+use std::str::FromStr;++use async_trait::async_trait;+use common_enums::MerchantCategoryCode;use common_utils::{- crypto::Encryptable, encryption::Encryption, errors::CustomResult, pii,- types::keymanager::ToEncryptable,+ crypto::Encryptable,+ encryption::Encryption,+ errors::{CustomResult, ValidationError},+ pii,+ types::keymanager::{Identifier, KeyManagerState, ToEncryptable},};-use masking::Secret;+use error_stack::ResultExt;+use masking::{PeekInterface, Secret};use rustc_hash::FxHashMap;use serde_json::Value;-#[cfg(feature = "v1")]+use super::behaviour;+use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};+#[derive(Clone, Debug, router_derive::ToEncryption, serde::Serialize)]pub struct Authentication {pub authentication_id: common_utils::id_type::AuthenticationId,@@ -47,20 +57,69 @@ pub struct Authentication {pub ds_trans_id: Option<String>,pub directory_server_id: Option<String>,pub acquirer_country_code: Option<String>,- pub service_details: Option<Value>,pub organization_id: common_utils::id_type::OrganizationId,+ pub mcc: Option<MerchantCategoryCode>,+ pub currency: Option<common_enums::Currency>,+ pub billing_country: Option<String>,+ pub shipping_country: Option<String>,+ pub issuer_country: Option<String>,+ pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub latest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub platform: Option<api_models::payments::DeviceChannel>,+ pub device_type: Option<String>,+ pub device_brand: Option<String>,+ pub device_os: Option<String>,+ pub device_display: Option<String>,+ pub browser_name: Option<String>,+ pub browser_version: Option<String>,+ pub issuer_id: Option<String>,+ pub scheme_name: Option<String>,+ pub exemption_requested: Option<bool>,+ pub exemption_accepted: Option<bool>,+ pub service_details: Option<Value>,pub authentication_client_secret: Option<String>,pub force_3ds_challenge: Option<bool>,pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,pub return_url: Option<String>,- pub amount: Option<common_utils::types::MinorUnit>,- pub currency: Option<common_enums::Currency>,#[encrypt(ty = Value)]- pub billing_address: Option<Encryptable<crate::address::Address>>,+ pub billing_address: Option<Encryptable<Secret<Value>>>,#[encrypt(ty = Value)]- pub shipping_address: Option<Encryptable<crate::address::Address>>,+ pub shipping_address: Option<Encryptable<Secret<Value>>>,pub browser_info: Option<Value>,pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,+ pub profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,+ pub challenge_code: Option<String>,+ pub challenge_cancel: Option<String>,+ pub challenge_code_reason: Option<String>,+ pub message_extension: Option<pii::SecretSerdeValue>,+ pub challenge_request_key: Option<String>,+ pub customer_details: Option<Encryption>,+ pub amount: Option<common_utils::types::MinorUnit>,+ pub merchant_country_code: Option<String>,+}++impl Authentication {+ pub fn is_separate_authn_required(&self) -> bool {+ self.maximum_supported_version+ .as_ref()+ .is_some_and(|version| version.get_major() == 2)+ }++ // get authentication_connector from authentication record and check if it is jwt flow+ pub fn is_jwt_flow(&self) -> CustomResult<bool, ValidationError> {+ Ok(self+ .authentication_connector+ .clone()+ .map(|connector| {+ common_enums::AuthenticationConnectors::from_str(&connector)+ .change_context(ValidationError::InvalidValue {+ message: "failed to parse authentication_connector".to_string(),+ })+ .map(|connector_enum| connector_enum.is_jwt_flow())+ })+ .transpose()?+ .unwrap_or(false))+ }}#[derive(Debug, Clone, serde::Serialize)]@@ -71,3 +130,540 @@ pub struct PgRedirectResponseForAuthentication {pub customer_id: Option<common_utils::id_type::CustomerId>,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,+ })+ }++ 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(+ state,+ common_utils::type_name!(Self),+ CryptoOperation::BatchDecrypt(EncryptedAuthentication::to_encryptable(+ EncryptedAuthentication {+ billing_address: other.billing_address,+ shipping_address: other.shipping_address,+ },+ )),+ Identifier::Merchant(other.merchant_id.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(encrypted_data)+ .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),+ Identifier::Merchant(other.merchant_id.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,+ })+ }++ 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,+ })+ }+}++#[derive(Debug)]+pub enum AuthenticationUpdate {+ PreAuthenticationVersionCallUpdate {+ maximum_supported_3ds_version: common_utils::types::SemanticVersion,+ message_version: common_utils::types::SemanticVersion,+ },+ PreAuthenticationThreeDsMethodCall {+ threeds_server_transaction_id: String,+ three_ds_method_data: Option<String>,+ three_ds_method_url: Option<String>,+ acquirer_bin: Option<String>,+ acquirer_merchant_id: Option<String>,+ connector_metadata: Option<Value>,+ },+ PreAuthenticationUpdate {+ threeds_server_transaction_id: String,+ maximum_supported_3ds_version: common_utils::types::SemanticVersion,+ connector_authentication_id: String,+ three_ds_method_data: Option<String>,+ three_ds_method_url: Option<String>,+ message_version: common_utils::types::SemanticVersion,+ connector_metadata: Option<Value>,+ authentication_status: common_enums::AuthenticationStatus,+ acquirer_bin: Option<String>,+ acquirer_merchant_id: Option<String>,+ directory_server_id: Option<String>,+ acquirer_country_code: Option<String>,+ billing_address: Box<Option<Encryptable<Secret<Value>>>>,+ shipping_address: Box<Option<Encryptable<Secret<Value>>>>,+ browser_info: Box<Option<Value>>,+ email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,+ scheme_id: Option<String>,+ merchant_category_code: Option<MerchantCategoryCode>,+ merchant_country_code: Option<String>,+ billing_country: Option<String>,+ shipping_country: Option<String>,+ earliest_supported_version: Option<common_utils::types::SemanticVersion>,+ latest_supported_version: Option<common_utils::types::SemanticVersion>,+ },+ AuthenticationUpdate {+ trans_status: common_enums::TransactionStatus,+ authentication_type: common_enums::DecoupledAuthenticationType,+ acs_url: Option<String>,+ challenge_request: Option<String>,+ acs_reference_number: Option<String>,+ acs_trans_id: Option<String>,+ acs_signed_content: Option<String>,+ connector_metadata: Option<Value>,+ authentication_status: common_enums::AuthenticationStatus,+ ds_trans_id: Option<String>,+ eci: Option<String>,+ challenge_code: Option<String>,+ challenge_cancel: Option<String>,+ challenge_code_reason: Option<String>,+ message_extension: Option<pii::SecretSerdeValue>,+ challenge_request_key: Option<String>,+ device_type: Option<String>,+ device_brand: Option<String>,+ device_os: Option<String>,+ device_display: Option<String>,+ },+ PostAuthenticationUpdate {+ trans_status: common_enums::TransactionStatus,+ eci: Option<String>,+ authentication_status: common_enums::AuthenticationStatus,+ challenge_cancel: Option<String>,+ challenge_code_reason: Option<String>,+ },+ ErrorUpdate {+ error_message: Option<String>,+ error_code: Option<String>,+ authentication_status: common_enums::AuthenticationStatus,+ connector_authentication_id: Option<String>,+ },+ PostAuthorizationUpdate {+ authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,+ },+ AuthenticationStatusUpdate {+ trans_status: common_enums::TransactionStatus,+ authentication_status: common_enums::AuthenticationStatus,+ },+}++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,+ } => 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,+ },+ }+ }+}diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rsindex 9e9f4712f2..c98bcb7d84 100644--- a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs@@ -3,7 +3,7 @@ use error_stack::{Report, ResultExt};use serde::{Deserialize, Serialize};use crate::{- address,+ address, authentication,errors::api_error_response::ApiErrorResponse,payment_method_data::{Card, PaymentMethodData},router_request_types::BrowserInformation,@@ -182,5 +182,16 @@ pub struct ExternalThreeDSConnectorMetadata {#[derive(Clone, Debug)]pub struct AuthenticationStore {pub cavv: Option<masking::Secret<String>>,- pub authentication: diesel_models::authentication::Authentication,+ pub authentication: authentication::Authentication,+}++#[derive(Clone, Debug)]+pub struct AuthenticationInfo {+ pub billing_address: Option<address::Address>,+ pub shipping_address: Option<address::Address>,+ pub browser_info: Option<BrowserInformation>,+ pub email: Option<Email>,+ pub device_details: Option<api_models::payments::DeviceDetails>,+ pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,+ pub merchant_country_code: Option<common_enums::CountryAlpha2>,}diff --git a/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs b/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rsindex 0ffa3d0186..2205f5e711 100644--- a/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs@@ -119,6 +119,7 @@ pub struct PreAuthenticationDetails {pub message_version: Option<common_utils::types::SemanticVersion>,pub connector_metadata: Option<serde_json::Value>,pub directory_server_id: Option<String>,+ pub scheme_id: Option<String>,}#[derive(Debug, Clone)]diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rsindex 28988001c8..3aaf658288 100644--- a/crates/hyperswitch_domain_models/src/router_response_types.rs+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs@@ -642,6 +642,7 @@ pub enum AuthenticationResponseData {message_version: common_utils::types::SemanticVersion,connector_metadata: Option<serde_json::Value>,directory_server_id: Option<String>,+ scheme_id: Option<String>,},AuthNResponse {authn_flow_type: AuthNFlowType,diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex 5185ac676d..e50fe7dc8b 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -987,6 +987,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::subscription::CancelSubscriptionRequest,api_models::subscription::CancelSubscriptionResponse,api_models::subscription::SubscriptionItemType,+ api_models::payments::DeviceDetails,common_types::payments::SdkDisplayMode,common_types::payments::CustomMessage,common_types::payments::CustomTerms,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex c82f827492..7cd477ea13 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -853,6 +853,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::tokenization::GenericTokenizationResponse,api_models::tokenization::DeleteTokenDataRequest,api_models::tokenization::DeleteTokenDataResponse,+ api_models::payments::DeviceDetails,common_types::payments::PaymentMethodsConfig,common_types::payments::PaymentMethodConfig,common_types::payments::CustomTerms,diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rsindex a38b7d841c..14edf75f0d 100644--- a/crates/router/src/core/authentication.rs+++ b/crates/router/src/core/authentication.rs@@ -7,6 +7,7 @@ use api_models::payments;use common_enums::Currency;use common_utils::errors::CustomResult;use error_stack::ResultExt;+use hyperswitch_domain_models::authentication;use masking::ExposeInterface;use super::errors::StorageErrorExt;@@ -16,7 +17,6 @@ use crate::{types::{self as core_types, api,domain::{self},- storage,},utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata,};@@ -36,7 +36,7 @@ pub async fn perform_authentication(currency: Option<Currency>,message_category: api::authentication::MessageCategory,device_channel: payments::DeviceChannel,- authentication_data: storage::Authentication,+ authentication_data: authentication::Authentication,return_url: Option<String>,sdk_information: Option<payments::SdkInformation>,threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,@@ -54,9 +54,9 @@ pub async fn perform_authentication(authentication_connector.clone(),payment_method_data,payment_method,- billing_address,- shipping_address,- browser_details,+ billing_address.clone(),+ shipping_address.clone(),+ browser_details.clone(),amount,currency,message_category,@@ -64,9 +64,9 @@ pub async fn perform_authentication(merchant_connector_account,authentication_data.clone(),return_url,- sdk_information,+ sdk_information.clone(),threeds_method_comp_ind,- email,+ email.clone(),webhook_url,three_ds_requestor_url,psd2_sca_exemption_type,@@ -79,13 +79,26 @@ pub async fn perform_authentication(router_data,)).await?;- let authentication = utils::update_trackers(++ let authentication_info =+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {+ billing_address: Some(billing_address),+ shipping_address,+ browser_info: browser_details,+ email,+ device_details: sdk_information+ .and_then(|sdk_information| sdk_information.device_details),+ merchant_category_code: None,+ merchant_country_code: None,+ };+ let authentication = Box::pin(utils::update_trackers(state,response.clone(),authentication_data,None,merchant_key_store,- )+ authentication_info,+ )).await?;response.response@@ -109,6 +122,7 @@ pub async fn perform_post_authentication(hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,ApiErrorResponse,> {+ let key_state = &state.into();let (authentication_connector, three_ds_connector_account) =utils::get_authentication_connector_data(state, key_store, &business_profile, None).await?;let is_pull_mechanism_enabled =@@ -122,6 +136,8 @@ pub async fn perform_post_authentication(.find_authentication_by_merchant_id_authentication_id(&business_profile.merchant_id,&authentication_id,+ key_store,+ key_state,).await.to_not_found_response(ApiErrorResponse::InternalServerError)@@ -147,7 +163,27 @@ pub async fn perform_post_authentication(let router_data =utils::do_auth_connector_call(state, authentication_connector.to_string(), router_data).await?;- utils::update_trackers(state, router_data, authentication, None, key_store).await?++ let authentication_info =+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {+ billing_address: None,+ shipping_address: None,+ browser_info: None,+ email: None,+ device_details: None,+ merchant_category_code: None,+ merchant_country_code: None,+ };++ utils::update_trackers(+ state,+ router_data,+ authentication,+ None,+ key_store,+ authentication_info,+ )+ .await?} else {// trigger in case of webhook flowauthentication@@ -186,6 +222,8 @@ pub async fn perform_pre_authentication(organization_id: common_utils::id_type::OrganizationId,force_3ds_challenge: Option<bool>,psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,+ billing_address: Option<hyperswitch_domain_models::address::Address>,+ shipping_address: Option<hyperswitch_domain_models::address::Address>,) -> CustomResult<hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,ApiErrorResponse,@@ -207,6 +245,7 @@ pub async fn perform_pre_authentication(organization_id,force_3ds_challenge,psd2_sca_exemption_type,+ key_store,).await?;@@ -227,12 +266,24 @@ pub async fn perform_pre_authentication().await?;+ let authentication_info =+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {+ billing_address: billing_address.clone(),+ shipping_address: shipping_address.clone(),+ browser_info: None,+ email: None,+ device_details: None,+ merchant_category_code: None,+ merchant_country_code: None,+ };+let updated_authentication = utils::update_trackers(state,router_data,authentication,acquirer_details.clone(),key_store,+ authentication_info,).await?;// from version call response, we will get to know the maximum supported 3ds version.@@ -260,12 +311,24 @@ pub async fn perform_pre_authentication(let router_data =utils::do_auth_connector_call(state, authentication_connector_name, router_data).await?;+ let authentication_info =+ hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {+ billing_address,+ shipping_address,+ browser_info: None,+ email: None,+ device_details: None,+ merchant_category_code: None,+ merchant_country_code: None,+ };+let authentication_update = utils::update_trackers(state,router_data,authentication,acquirer_details,key_store,+ authentication_info,).await?;diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rsindex fb74955ab6..ba2e0556a7 100644--- a/crates/router/src/core/authentication/transformers.rs+++ b/crates/router/src/core/authentication/transformers.rs@@ -4,6 +4,7 @@ use api_models::payments;use common_enums::PaymentMethod;use common_utils::ext_traits::ValueExt;use error_stack::ResultExt;+use hyperswitch_domain_models::authentication;use crate::{core::{@@ -11,7 +12,7 @@ use crate::{payments::helpers as payments_helpers,},types::{- self, domain, storage,+ self, domain,transformers::{ForeignFrom, ForeignTryFrom},},utils::ext_traits::OptionExt,@@ -38,7 +39,7 @@ pub fn construct_authentication_router_data(message_category: types::api::authentication::MessageCategory,device_channel: payments::DeviceChannel,merchant_connector_account: payments_helpers::MerchantConnectorAccountType,- authentication_data: storage::Authentication,+ authentication_data: authentication::Authentication,return_url: Option<String>,sdk_information: Option<payments::SdkInformation>,threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,@@ -87,7 +88,7 @@ pub fn construct_post_authentication_router_data(authentication_connector: String,business_profile: domain::Profile,merchant_connector_account: payments_helpers::MerchantConnectorAccountType,- authentication_data: &storage::Authentication,+ authentication_data: &authentication::Authentication,payment_id: &common_utils::id_type::PaymentId,) -> RouterResult<types::authentication::ConnectorPostAuthenticationRouterData> {let threeds_server_transaction_id = authentication_datadiff --git a/crates/router/src/core/authentication/types.rs b/crates/router/src/core/authentication/types.rsindex 419f2b427a..a2087716b8 100644--- a/crates/router/src/core/authentication/types.rs+++ b/crates/router/src/core/authentication/types.rs@@ -1,18 +1,19 @@use error_stack::{Report, ResultExt};-pub use hyperswitch_domain_models::router_request_types::authentication::{- AcquirerDetails, ExternalThreeDSConnectorMetadata, PreAuthenticationData, ThreeDsMethodData,+pub use hyperswitch_domain_models::{+ authentication,+ router_request_types::authentication::{+ AcquirerDetails, ExternalThreeDSConnectorMetadata, PreAuthenticationData, ThreeDsMethodData,+ },};-use crate::{- core::errors,- types::{storage, transformers::ForeignTryFrom},- utils::OptionExt,-};+use crate::{core::errors, types::transformers::ForeignTryFrom, utils::OptionExt};-impl ForeignTryFrom<&storage::Authentication> for PreAuthenticationData {+impl ForeignTryFrom<&authentication::Authentication> for PreAuthenticationData {type Error = Report<errors::ApiErrorResponse>;- fn foreign_try_from(authentication: &storage::Authentication) -> Result<Self, Self::Error> {+ fn foreign_try_from(+ authentication: &authentication::Authentication,+ ) -> Result<Self, Self::Error> {let error_message = errors::ApiErrorResponse::UnprocessableEntity { message: "Pre Authentication must be completed successfully before Authentication can be performed".to_string() };let threeds_server_transaction_id = authentication.threeds_server_transaction_iddiff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rsindex 05156b8211..c22a381ebd 100644--- a/crates/router/src/core/authentication/utils.rs+++ b/crates/router/src/core/authentication/utils.rs@@ -1,7 +1,10 @@-use common_utils::ext_traits::AsyncExt;+use common_utils::{ext_traits::AsyncExt, types::keymanager::ToEncryptable};use error_stack::ResultExt;-use hyperswitch_domain_models::router_data_v2::ExternalAuthenticationFlowData;-use masking::ExposeInterface;+use hyperswitch_domain_models::{+ authentication, router_data_v2::ExternalAuthenticationFlowData, router_request_types,+ type_encryption::AsyncLift,+};+use masking::{ExposeInterface, PeekInterface};use crate::{consts,@@ -13,8 +16,8 @@ use crate::{routes::SessionState,services::{self, execute_connector_processing_step},types::{- api, authentication::AuthenticationResponseData, domain, storage,- transformers::ForeignFrom, RouterData,+ api, authentication::AuthenticationResponseData, domain, transformers::ForeignFrom,+ RouterData,},utils::OptionExt,};@@ -52,13 +55,16 @@ pub fn get_connector_data_if_separate_authn_supported(}}+#[allow(clippy::too_many_arguments)]pub async fn update_trackers<F: Clone, Req>(state: &SessionState,router_data: RouterData<F, Req, AuthenticationResponseData>,- authentication: storage::Authentication,+ authentication: authentication::Authentication,acquirer_details: Option<super::types::AcquirerDetails>,merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,-) -> RouterResult<storage::Authentication> {+ authentication_info: router_request_types::authentication::AuthenticationInfo,+) -> RouterResult<authentication::Authentication> {+ let key_manager_state = state.into();let authentication_update = match router_data.response {Ok(response) => match response {AuthenticationResponseData::PreAuthNResponse {@@ -70,29 +76,136 @@ pub async fn update_trackers<F: Clone, Req>(message_version,connector_metadata,directory_server_id,- } => storage::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: common_enums::AuthenticationStatus::Pending,- acquirer_bin: acquirer_details- .as_ref()- .map(|acquirer_details| acquirer_details.acquirer_bin.clone()),- acquirer_merchant_id: acquirer_details+ scheme_id,+ } => {+ let billing_details_encoded = authentication_info+ .billing_address+ .clone()+ .map(|billing| {+ common_utils::ext_traits::Encode::encode_to_value(&billing)+ .map(masking::Secret::<serde_json::Value>::new)+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encode billing details to serde_json::Value")?;++ let shipping_details_encoded = authentication_info+ .shipping_address+ .clone()+ .map(|shipping| {+ common_utils::ext_traits::Encode::encode_to_value(&shipping)+ .map(masking::Secret::<serde_json::Value>::new)+ })+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encode shipping details to serde_json::Value")?;++ let encrypted_data = domain::types::crypto_operation(+ &key_manager_state,+ common_utils::type_name!(authentication::Authentication),+ domain::types::CryptoOperation::BatchEncrypt(+ authentication::UpdateEncryptableAuthentication::to_encryptable(+ authentication::UpdateEncryptableAuthentication {+ billing_address: billing_details_encoded,+ shipping_address: shipping_details_encoded,+ },+ ),+ ),+ common_utils::types::keymanager::Identifier::Merchant(+ merchant_key_store.merchant_id.clone(),+ ),+ merchant_key_store.key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt authentication data".to_string())?;++ let browser_info = authentication_info+ .browser_info.as_ref()- .map(|acquirer_details| acquirer_details.acquirer_merchant_id.clone()),- acquirer_country_code: acquirer_details- .and_then(|acquirer_details| acquirer_details.acquirer_country_code),- directory_server_id,- billing_address: None,- shipping_address: None,- browser_info: Box::new(None),- email: None,- },+ .map(common_utils::ext_traits::Encode::encode_to_value)+ .transpose()+ .change_context(errors::ApiErrorResponse::InvalidDataValue {+ field_name: "browser_information",+ })?;++ let encrypted_data =+ authentication::FromRequestEncryptableAuthentication::from_encryptable(+ encrypted_data,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Unable to get encrypted data for authentication after encryption",+ )?;++ let email_encrypted = authentication_info+ .clone()+ .async_lift(|inner| async {+ domain::types::crypto_operation(+ &key_manager_state,+ common_utils::type_name!(authentication::Authentication),+ domain::types::CryptoOperation::EncryptOptional(+ inner.map(|inner| inner.expose()),+ ),+ common_utils::types::keymanager::Identifier::Merchant(+ merchant_key_store.merchant_id.clone(),+ ),+ merchant_key_store.key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt email")?;++ authentication::AuthenticationUpdate::PreAuthenticationUpdate {+ threeds_server_transaction_id,+ maximum_supported_3ds_version: maximum_supported_3ds_version.clone(),+ connector_authentication_id,+ three_ds_method_data,+ three_ds_method_url,+ message_version,+ connector_metadata,+ authentication_status: common_enums::AuthenticationStatus::Pending,+ acquirer_bin: acquirer_details+ .as_ref()+ .map(|acquirer_details| acquirer_details.acquirer_bin.clone()),+ acquirer_merchant_id: acquirer_details+ .as_ref()+ .map(|acquirer_details| acquirer_details.acquirer_merchant_id.clone()),+ acquirer_country_code: acquirer_details+ .and_then(|acquirer_details| acquirer_details.acquirer_country_code),+ directory_server_id,+ billing_address: Box::new(encrypted_data.billing_address),+ shipping_address: Box::new(encrypted_data.shipping_address),+ browser_info: Box::new(browser_info),+ email: email_encrypted,+ scheme_id,+ merchant_category_code: authentication_info.merchant_category_code,+ merchant_country_code: authentication_info+ .merchant_country_code+ .map(|merchant_country_code| merchant_country_code.to_string()),+ billing_country: authentication_info.billing_address.and_then(+ |billing_address| {+ billing_address.address.and_then(|address| {+ address.country.map(|country| country.to_string())+ })+ },+ ),+ shipping_country: authentication_info.shipping_address.and_then(+ |shipping_address| {+ shipping_address.address.and_then(|address| {+ address.country.map(|country| country.to_string())+ })+ },+ ),+ earliest_supported_version: Some(maximum_supported_3ds_version.clone()),+ latest_supported_version: Some(maximum_supported_3ds_version.clone()),+ }+ }AuthenticationResponseData::AuthNResponse {authn_flow_type,authentication_value,@@ -124,7 +237,7 @@ pub async fn update_trackers<F: Clone, Req>(let authentication_status =common_enums::AuthenticationStatus::foreign_from(trans_status.clone());- storage::AuthenticationUpdate::AuthenticationUpdate {+ authentication::AuthenticationUpdate::AuthenticationUpdate {trans_status,acs_url: authn_flow_type.get_acs_url(),challenge_request: authn_flow_type.get_challenge_request(),@@ -141,6 +254,22 @@ pub async fn update_trackers<F: Clone, Req>(challenge_cancel,challenge_code_reason,message_extension,+ device_type: authentication_info+ .device_details+ .as_ref()+ .and_then(|device_details| device_details.device_type.clone()),+ device_brand: authentication_info+ .device_details+ .as_ref()+ .and_then(|device_details| device_details.device_brand.clone()),+ device_os: authentication_info+ .device_details+ .as_ref()+ .and_then(|device_details| device_details.device_os.clone()),+ device_display: authentication_info+ .device_details+ .as_ref()+ .and_then(|device_details| device_details.device_display.clone()),}}AuthenticationResponseData::PostAuthNResponse {@@ -165,7 +294,7 @@ pub async fn update_trackers<F: Clone, Req>(}).await.transpose()?;- storage::AuthenticationUpdate::PostAuthenticationUpdate {+ authentication::AuthenticationUpdate::PostAuthenticationUpdate {authentication_status: common_enums::AuthenticationStatus::foreign_from(trans_status.clone(),),@@ -177,7 +306,7 @@ pub async fn update_trackers<F: Clone, Req>(}AuthenticationResponseData::PreAuthVersionCallResponse {maximum_supported_3ds_version,- } => storage::AuthenticationUpdate::PreAuthenticationVersionCallUpdate {+ } => authentication::AuthenticationUpdate::PreAuthenticationVersionCallUpdate {message_version: maximum_supported_3ds_version.clone(),maximum_supported_3ds_version,},@@ -186,7 +315,7 @@ pub async fn update_trackers<F: Clone, Req>(three_ds_method_data,three_ds_method_url,connector_metadata,- } => storage::AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {+ } => authentication::AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {threeds_server_transaction_id,three_ds_method_data,three_ds_method_url,@@ -198,7 +327,7 @@ pub async fn update_trackers<F: Clone, Req>(.map(|acquirer_details| acquirer_details.acquirer_merchant_id),},},- Err(error) => storage::AuthenticationUpdate::ErrorUpdate {+ Err(error) => authentication::AuthenticationUpdate::ErrorUpdate {connector_authentication_id: error.connector_transaction_id,authentication_status: common_enums::AuthenticationStatus::Failed,error_message: error@@ -213,6 +342,8 @@ pub async fn update_trackers<F: Clone, Req>(.update_authentication_by_merchant_id_authentication_id(authentication,authentication_update,+ merchant_key_store,+ &key_manager_state,).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -242,7 +373,8 @@ pub async fn create_new_authentication(organization_id: common_utils::id_type::OrganizationId,force_3ds_challenge: Option<bool>,psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,-) -> RouterResult<storage::Authentication> {+ merchant_key_store: &domain::MerchantKeyStore,+) -> RouterResult<authentication::Authentication> {let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id(consts::AUTHENTICATION_ID_PREFIX,);@@ -250,15 +382,23 @@ pub async fn create_new_authentication("{}_secret",authentication_id.get_string_repr())));- let new_authorization = storage::AuthenticationNew {++ let key_manager_state = (state).into();++ let current_time = common_utils::date_time::now();++ let new_authentication = authentication::Authentication {authentication_id: authentication_id.clone(),merchant_id,authentication_connector: Some(authentication_connector),connector_authentication_id: None,+ authentication_data: None,payment_method_id: format!("eph_{token}"),authentication_type: None,authentication_status: common_enums::AuthenticationStatus::Started,authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused,+ created_at: current_time,+ modified_at: current_time,error_message: None,error_code: None,connector_metadata: None,@@ -275,7 +415,6 @@ pub async fn create_new_authentication(three_ds_method_url: None,acs_url: None,challenge_request: None,- challenge_request_key: None,acs_reference_number: None,acs_trans_id: None,acs_signed_content: None,@@ -285,14 +424,31 @@ pub async fn create_new_authentication(ds_trans_id: None,directory_server_id: None,acquirer_country_code: None,- service_details: None,organization_id,+ mcc: None,+ amount: None,+ currency: None,+ billing_country: None,+ shipping_country: None,+ issuer_country: None,+ earliest_supported_version: None,+ latest_supported_version: None,+ platform: None,+ device_type: None,+ device_brand: None,+ device_os: None,+ device_display: None,+ browser_name: None,+ browser_version: None,+ issuer_id: None,+ scheme_name: None,+ exemption_requested: None,+ exemption_accepted: None,+ service_details: None,authentication_client_secret,force_3ds_challenge,psd2_sca_exemption_type,return_url: None,- amount: None,- currency: None,billing_address: None,shipping_address: None,browser_info: None,@@ -302,11 +458,14 @@ pub async fn create_new_authentication(challenge_cancel: None,challenge_code_reason: None,message_extension: None,+ challenge_request_key: None,customer_details: None,+ merchant_country_code: None,};+state.store- .insert_authentication(new_authorization)+ .insert_authentication(&key_manager_state, merchant_key_store, new_authentication).await.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {message: format!(diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 7b321daaba..f40e2bd8ef 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -3747,9 +3747,15 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {.authentication_id.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("missing authentication_id in payment_attempt")?;+ let key_manager_state = &(state).into();let authentication = state.store- .find_authentication_by_merchant_id_authentication_id(&merchant_id, &authentication_id)+ .find_authentication_by_merchant_id_authentication_id(+ &merchant_id,+ &authentication_id,+ platform.get_processor().get_key_store(),+ key_manager_state,+ ).await.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {id: authentication_id.get_string_repr().to_string(),@@ -10772,6 +10778,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(};let db = &*state.store;+ let key_manager_state = &(&(state)).into();let merchant_id = platform.get_processor().get_account().get_id();let storage_scheme = platform.get_processor().get_account().storage_scheme;@@ -10875,6 +10882,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(None,).await?;+let authentication = db.find_authentication_by_merchant_id_authentication_id(merchant_id,@@ -10883,6 +10891,8 @@ pub async fn payment_external_authentication<F: Clone + Sync>(.clone().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("missing authentication_id in payment_attempt")?,+ platform.get_processor().get_key_store(),+ key_manager_state,).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)@@ -10960,7 +10970,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(req.device_channel,authentication.clone(),return_url,- req.sdk_information,+ req.sdk_information.clone(),req.threeds_method_comp_ind,optional_customer.and_then(|customer| customer.email.map(pii::Email::from)),webhook_url,@@ -10971,7 +10981,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(authentication.psd2_sca_exemption_type,).await?;- let authentication = external_authentication_update_trackers(+ let authentication = Box::pin(external_authentication_update_trackers(&state,auth_response,authentication.clone(),@@ -10981,7 +10991,11 @@ pub async fn payment_external_authentication<F: Clone + Sync>(None,None,None,- )+ req.sdk_information+ .and_then(|sdk_information| sdk_information.device_details),+ None,+ None,+ )).await?;authentication::AuthenticationResponse::try_from(authentication)?} else {@@ -11036,6 +11050,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(acs_signed_content: authentication_response.acs_signed_content,three_ds_requestor_url: authentication_details.three_ds_requestor_url,three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url,+ error_message: authentication_response.error_message,},))}diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex f47f753f23..7995a176da 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -1034,6 +1034,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forcard,token,}) => {+ let billing_address = payment_data.address.get_payment_method_billing().cloned();+ let shipping = payment_data.address.get_shipping().cloned();let authentication_store = Box::pin(authentication::perform_pre_authentication(state,key_store,@@ -1045,6 +1047,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forpayment_data.payment_attempt.organization_id.clone(),payment_data.payment_intent.force_3ds_challenge,payment_data.payment_intent.psd2_sca_exemption_type,+ billing_address,+ shipping,)).await?;if authentication_store@@ -1246,6 +1250,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> formandate_type,).await?;+ let key_manager_state = &(state).into();if let Some(unified_authentication_service_flow) = unified_authentication_service_flow {match unified_authentication_service_flow {@@ -1375,7 +1380,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forNone,None,None,- None+ None,+ key_store).await?;let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {@@ -1422,11 +1428,12 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> foracquirer_bin,acquirer_merchant_id,acquirer_country_code,+ Some(payment_data.payment_intent.amount),+ payment_data.payment_intent.currency,None,None,None,- None,- None+ key_store).await?;let acquirer_configs = authentication@@ -1459,18 +1466,27 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to parse webhook url")?;+ let merchant_category_code = business_profile.merchant_category_code.clone().or(metadata.clone().and_then(|metadata| metadata.merchant_category_code.clone()));+let merchant_details = Some(unified_authentication_service::MerchantDetails {merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()),merchant_name: acquirer_configs.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)),- merchant_category_code: business_profile.merchant_category_code.clone().or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)),+ merchant_category_code: merchant_category_code.clone(),endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix),three_ds_requestor_url: business_profile.authentication_connector_details.clone().map(|details| details.three_ds_requestor_url),three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id),three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name),- merchant_country_code: merchant_country_code.map(common_types::payments::MerchantCountryCode::new),+ merchant_country_code: merchant_country_code.clone().map(common_types::payments::MerchantCountryCode::new),notification_url,});let domain_address = payment_data.address.get_payment_method_billing();+ let shipping = payment_data.address.get_shipping();+ let browser_info = payment_data.payment_attempt.browser_info+ .clone()+ .parse_value("BrowserInfo")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse browser_info")?;+ let email = payment_data.email.clone();let pre_auth_response = uas_utils::types::ExternalAuthentication::pre_authentication(state,@@ -1493,17 +1509,20 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forauthentication.acquirer_merchant_id.clone(),).await?;- let updated_authentication = uas_utils::utils::external_authentication_update_trackers(+ let updated_authentication = Box::pin(uas_utils::utils::external_authentication_update_trackers(state,pre_auth_response,authentication.clone(),acquirer_details,key_store,+ domain_address.cloned(),+ shipping.cloned(),+ email,+ browser_info,None,- None,- None,- None,- ).await?;+ merchant_category_code,+ merchant_country_code.map(common_types::payments::MerchantCountryCode::new),+ )).await?;let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {cavv: None, // since in case of pre_authentication cavv is not presentauthentication: updated_authentication.clone(),@@ -1558,6 +1577,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.find_authentication_by_merchant_id_authentication_id(&business_profile.merchant_id,&authentication_id,+ key_store,+ key_manager_state,).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)@@ -1586,6 +1607,9 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forNone,None,None,+ None,+ None,+ None,).await?} else {authentication@@ -1773,7 +1797,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for};let status_handler_for_authentication_results =- |authentication: &storage::Authentication| {+ |authentication: &hyperswitch_domain_models::authentication::Authentication| {if authentication.authentication_status.is_failed() {(storage_enums::IntentStatus::Failed,diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex 666f98d6cf..d1e6d17370 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -9,7 +9,7 @@ use common_enums::AuthorizationStatus;use common_utils::ext_traits::ValueExt;use common_utils::{ext_traits::{AsyncExt, Encode},- types::{ConnectorTransactionId, MinorUnit},+ types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit},};use error_stack::{report, ResultExt};use futures::FutureExt;@@ -2191,10 +2191,10 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>();payment_data.payment_attempt = payment_attempt;-+ let key_manager_state: KeyManagerState = state.into();payment_data.authentication = match payment_data.authentication {Some(mut authentication_store) => {- let authentication_update = storage::AuthenticationUpdate::PostAuthorizationUpdate {+ let authentication_update = hyperswitch_domain_models::authentication::AuthenticationUpdate::PostAuthorizationUpdate {authentication_lifecycle_status: enums::AuthenticationLifecycleStatus::Used,};let updated_authentication = state@@ -2202,6 +2202,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(.update_authentication_by_merchant_id_authentication_id(authentication_store.authentication,authentication_update,+ key_store,+ &key_manager_state,).await.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rsindex b5f6209894..fd462b6e24 100644--- a/crates/router/src/core/payments/operations/payment_status.rs+++ b/crates/router/src/core/payments/operations/payment_status.rs@@ -449,30 +449,35 @@ async fn get_tracker_for_sync<};let merchant_id = payment_intent.merchant_id.clone();-- let authentication_store = if let Some(ref authentication_id) =- payment_attempt.authentication_id- {- let authentication = db- .find_authentication_by_merchant_id_authentication_id(&merchant_id, authentication_id)- .await- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)- .attach_printable_lazy(|| {- format!(- "Error while fetching authentication record with authentication_id {}",- authentication_id.get_string_repr()+ let key_manager_state = &(state).into();++ let authentication_store =+ if let Some(ref authentication_id) = payment_attempt.authentication_id {+ let authentication = db+ .find_authentication_by_merchant_id_authentication_id(+ &merchant_id,+ authentication_id,+ platform.get_processor().get_key_store(),+ key_manager_state,)- })?;+ .await+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!(+ "Error while fetching authentication record with authentication_id {}",+ authentication_id.get_string_repr()+ )+ })?;- Some(+ Some(hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {authentication,cavv: None, // marking this as None since we don't need authentication value in payment status flow},)- } else {- None- };+ } else {+ None+ };let payment_link_data = payment_intent.payment_link_iddiff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rsindex 05bd6dfd97..837b32d527 100644--- a/crates/router/src/core/unified_authentication_service.rs+++ b/crates/router/src/core/unified_authentication_service.rs@@ -22,11 +22,8 @@ use api_models::{payments::{self, CustomerDetails},};#[cfg(feature = "v1")]-use common_utils::{- errors::CustomResult, ext_traits::ValueExt, types::keymanager::ToEncryptable,- types::AmountConvertor,-};-use diesel_models::authentication::{Authentication, AuthenticationNew};+use common_utils::{errors::CustomResult, ext_traits::ValueExt, types::AmountConvertor};+use diesel_models::authentication::Authentication;use error_stack::ResultExt;use hyperswitch_domain_models::{errors::api_error_response::ApiErrorResponse,@@ -191,7 +188,7 @@ impl UnifiedAuthenticationService for ClickToPay {authentication_id: &common_utils::id_type::AuthenticationId,payment_method: common_enums::PaymentMethod,merchant_id: &common_utils::id_type::MerchantId,- _authentication: Option<&Authentication>,+ _authentication: Option<&hyperswitch_domain_models::authentication::Authentication>,) -> RouterResult<UasPostAuthenticationRouterData> {let post_authentication_data = UasPostAuthenticationRequestData {threeds_server_transaction_id: None,@@ -406,7 +403,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {currency: Option<common_enums::Currency>,message_category: MessageCategory,device_channel: payments::DeviceChannel,- authentication: Authentication,+ authentication: hyperswitch_domain_models::authentication::Authentication,return_url: Option<String>,sdk_information: Option<payments::SdkInformation>,threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,@@ -459,7 +456,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {currency: Option<common_enums::Currency>,message_category: MessageCategory,device_channel: payments::DeviceChannel,- authentication: Authentication,+ authentication: hyperswitch_domain_models::authentication::Authentication,return_url: Option<String>,sdk_information: Option<payments::SdkInformation>,threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,@@ -508,7 +505,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {}fn get_post_authentication_request_data(- authentication: Option<Authentication>,+ authentication: Option<hyperswitch_domain_models::authentication::Authentication>,) -> RouterResult<UasPostAuthenticationRequestData> {Ok(UasPostAuthenticationRequestData {// authentication.threeds_server_transaction_id is mandatory for post-authentication in ExternalAuthentication@@ -531,7 +528,7 @@ impl UnifiedAuthenticationService for ExternalAuthentication {authentication_id: &common_utils::id_type::AuthenticationId,payment_method: common_enums::PaymentMethod,_merchant_id: &common_utils::id_type::MerchantId,- authentication: Option<&Authentication>,+ authentication: Option<&hyperswitch_domain_models::authentication::Authentication>,) -> RouterResult<UasPostAuthenticationRouterData> {let authentication_data =<Self as UnifiedAuthenticationService>::get_post_authentication_request_data(@@ -581,7 +578,8 @@ pub async fn create_new_authentication(return_url: Option<String>,profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,customer_details: Option<common_utils::encryption::Encryption>,-) -> RouterResult<Authentication> {+ merchant_key_store: &domain::MerchantKeyStore,+) -> RouterResult<hyperswitch_domain_models::authentication::Authentication> {let service_details_value = service_details.map(serde_json::to_value).transpose()@@ -593,15 +591,23 @@ pub async fn create_new_authentication("{}_secret",authentication_id.get_string_repr())));- let new_authorization = AuthenticationNew {- authentication_id: authentication_id.to_owned(),++ let key_manager_state = (state).into();++ let current_time = common_utils::date_time::now();++ let new_authentication = hyperswitch_domain_models::authentication::Authentication {+ authentication_id: authentication_id.clone(),merchant_id,authentication_connector,connector_authentication_id: None,+ authentication_data: None,payment_method_id: "".to_string(),authentication_type: None,authentication_status,authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused,+ created_at: current_time,+ modified_at: current_time,error_message: None,error_code: None,connector_metadata: None,@@ -618,7 +624,6 @@ pub async fn create_new_authentication(three_ds_method_url: None,acs_url: None,challenge_request: None,- challenge_request_key: None,acs_reference_number: None,acs_trans_id: None,acs_signed_content: None,@@ -628,14 +633,31 @@ pub async fn create_new_authentication(ds_trans_id: None,directory_server_id: None,acquirer_country_code,- service_details: service_details_value,organization_id,+ mcc: None,+ amount,+ currency,+ billing_country: None,+ shipping_country: None,+ issuer_country: None,+ earliest_supported_version: None,+ latest_supported_version: None,+ platform: None,+ device_type: None,+ device_brand: None,+ device_os: None,+ device_display: None,+ browser_name: None,+ browser_version: None,+ issuer_id: None,+ scheme_name: None,+ exemption_requested: Some(psd2_sca_exemption_type.is_some()),+ exemption_accepted: None,+ service_details: service_details_value,authentication_client_secret,force_3ds_challenge,psd2_sca_exemption_type,return_url,- amount,- currency,billing_address: None,shipping_address: None,browser_info: None,@@ -645,11 +667,14 @@ pub async fn create_new_authentication(challenge_cancel: None,challenge_code_reason: None,message_extension: None,+ challenge_request_key: None,customer_details,+ merchant_country_code: None,};+state.store- .insert_authentication(new_authorization)+ .insert_authentication(&key_manager_state, merchant_key_store, new_authentication).await.to_duplicate_response(ApiErrorResponse::GenericDuplicateError {message: format!(@@ -785,6 +810,7 @@ pub async fn authentication_create_core(customer_details.clone().map(common_utils::encryption::Encryption::from),+ platform.get_processor().get_key_store(),).await?;@@ -847,7 +873,7 @@ pub async fn authentication_create_core(implForeignTryFrom<(- Authentication,+ hyperswitch_domain_models::authentication::Authentication,common_utils::types::MinorUnit,common_enums::Currency,common_utils::id_type::ProfileId,@@ -869,7 +895,7 @@ implcustomer_data,customer_id,): (- Authentication,+ hyperswitch_domain_models::authentication::Authentication,common_utils::types::MinorUnit,common_enums::Currency,common_utils::id_type::ProfileId,@@ -930,7 +956,7 @@ impl#[cfg(feature = "v1")]implForeignTryFrom<(- Authentication,+ hyperswitch_domain_models::authentication::Authentication,api_models::authentication::NextAction,common_utils::id_type::ProfileId,Option<payments::Address>,@@ -942,7 +968,7 @@ impltype Error = error_stack::Report<ApiErrorResponse>;fn foreign_try_from((authentication, next_action, profile_id, billing, shipping, browser_information, email): (- Authentication,+ hyperswitch_domain_models::authentication::Authentication,api_models::authentication::NextAction,common_utils::id_type::ProfileId,Option<payments::Address>,@@ -1007,10 +1033,16 @@ pub async fn authentication_eligibility_core(authentication_id: common_utils::id_type::AuthenticationId,) -> RouterResponse<AuthenticationEligibilityResponse> {let merchant_account = platform.get_processor().get_account();+ let key_manager_state = (&state).into();let merchant_id = merchant_account.get_id();let db = &*state.store;let authentication = db- .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)+ .find_authentication_by_merchant_id_authentication_id(+ merchant_id,+ &authentication_id,+ platform.get_processor().get_key_store(),+ &key_manager_state,+ ).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {id: authentication_id.get_string_repr().to_owned(),@@ -1028,8 +1060,6 @@ pub async fn authentication_eligibility_core(ensure_not_terminal_status(authentication.trans_status.clone())?;- let key_manager_state = (&state).into();-let profile_id = core_utils::get_profile_id_from_business_details(None,None,@@ -1106,16 +1136,19 @@ pub async fn authentication_eligibility_core(.change_context(ApiErrorResponse::InternalServerError)?;let merchant_country_code = authentication.acquirer_country_code.clone();+ let merchant_category_code = business_profile.merchant_category_code.or(metadata+ .clone()+ .and_then(|metadata| metadata.merchant_category_code));let merchant_details = Some(hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails {merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()),merchant_name: acquirer_details.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)),- merchant_category_code: business_profile.merchant_category_code.or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)),+ merchant_category_code: merchant_category_code.clone(),endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix),three_ds_requestor_url: business_profile.authentication_connector_details.map(|details| details.three_ds_requestor_url),three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id),three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name),- merchant_country_code: merchant_country_code.map(common_types::payments::MerchantCountryCode::new),+ merchant_country_code: merchant_country_code.clone().map(common_types::payments::MerchantCountryCode::new),notification_url,});@@ -1145,106 +1178,34 @@ pub async fn authentication_eligibility_core().await?;- let billing_details_encoded = req+ let domain_billing_address = req.billing.clone()- .map(|billing| {- common_utils::ext_traits::Encode::encode_to_value(&billing)- .map(masking::Secret::<serde_json::Value>::new)- })- .transpose()- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encode billing details to serde_json::Value")?;-- let shipping_details_encoded = req+ .map(hyperswitch_domain_models::address::Address::from);+ let domain_shipping_address = req.shipping.clone()- .map(|shipping| {- common_utils::ext_traits::Encode::encode_to_value(&shipping)- .map(masking::Secret::<serde_json::Value>::new)- })- .transpose()- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encode shipping details to serde_json::Value")?;-- let encrypted_data = domain::types::crypto_operation(- &key_manager_state,- common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication),- domain::types::CryptoOperation::BatchEncrypt(- hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication::to_encryptable(- hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication {- billing_address: billing_details_encoded,- shipping_address: shipping_details_encoded,- },- ),- ),- common_utils::types::keymanager::Identifier::Merchant(- platform- .get_processor().get_key_store()- .merchant_id- .clone(),- ),- platform.get_processor().get_key_store().key.peek(),- )- .await- .and_then(|val| val.try_into_batchoperation())- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt authentication data".to_string())?;-- let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Unable to get encrypted data for authentication after encryption")?;-- let email_encrypted = req- .clone()- .async_lift(|inner| async {- domain::types::crypto_operation(- &key_manager_state,- common_utils::type_name!(Authentication),- domain::types::CryptoOperation::EncryptOptional(inner.map(|inner| inner.expose())),- common_utils::types::keymanager::Identifier::Merchant(- platform.get_processor().get_key_store().merchant_id.clone(),- ),- platform.get_processor().get_key_store().key.peek(),- )- .await- .and_then(|val| val.try_into_optionaloperation())- })- .await- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt email")?;-- let browser_info = req- .browser_information- .as_ref()- .map(common_utils::ext_traits::Encode::encode_to_value)- .transpose()- .change_context(ApiErrorResponse::InvalidDataValue {- field_name: "browser_information",- })?;-- let updated_authentication = utils::external_authentication_update_trackers(+ .map(hyperswitch_domain_models::address::Address::from);+ let updated_authentication = Box::pin(utils::external_authentication_update_trackers(&state,pre_auth_response,authentication.clone(),None,platform.get_processor().get_key_store(),- encrypted_data- .billing_address- .map(common_utils::encryption::Encryption::from),- encrypted_data- .shipping_address- .map(common_utils::encryption::Encryption::from),- email_encrypted+ domain_billing_address,+ domain_shipping_address,+ req.email.clone(),+ req.browser_information.clone(),+ None,+ merchant_category_code,+ merchant_country_code.clone()- .map(common_utils::encryption::Encryption::from),- browser_info,- )+ .map(common_types::payments::MerchantCountryCode::new),+ )).await?;let response = AuthenticationEligibilityResponse::foreign_try_from((- updated_authentication,+ updated_authentication.clone(),req.get_next_action_api(state.base_url,authentication_id.get_string_repr().to_string(),@@ -1255,7 +1216,7 @@ pub async fn authentication_eligibility_core(req.get_billing_address(),req.get_shipping_address(),req.get_browser_information(),- email_encrypted,+ updated_authentication.email,))?;Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(@@ -1274,8 +1235,14 @@ pub async fn authentication_authenticate_core(let merchant_account = platform.get_processor().get_account();let merchant_id = merchant_account.get_id();let db = &*state.store;+ let key_manager_state = (&state).into();let authentication = db- .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)+ .find_authentication_by_merchant_id_authentication_id(+ merchant_id,+ &authentication_id,+ platform.get_processor().get_key_store(),+ &key_manager_state,+ ).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {id: authentication_id.get_string_repr().to_owned(),@@ -1290,10 +1257,6 @@ pub async fn authentication_authenticate_core(}).transpose()?;- ensure_not_terminal_status(authentication.trans_status.clone())?;-- let key_manager_state = (&state).into();-let profile_id = authentication.profile_id.clone();let business_profile = db@@ -1303,26 +1266,6 @@ pub async fn authentication_authenticate_core(id: profile_id.get_string_repr().to_owned(),})?;- let email_encrypted = authentication- .clone()- .async_lift(|inner| async {- domain::types::crypto_operation(- &key_manager_state,- common_utils::type_name!(Authentication),- domain::types::CryptoOperation::DecryptOptional(inner),- common_utils::types::keymanager::Identifier::Merchant(- platform.get_processor().get_key_store().merchant_id.clone(),- ),- platform.get_processor().get_key_store().key.peek(),- )- .await- .and_then(|val| val.try_into_optionaloperation())- })- .await- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Unable to decrypt email from authentication table")?;-let browser_info = authentication.browser_info.clone()@@ -1370,9 +1313,12 @@ pub async fn authentication_authenticate_core(req.device_channel,authentication.clone(),None,- req.sdk_information,+ req.sdk_information.clone(),req.threeds_method_comp_ind,- email_encrypted.map(common_utils::pii::Email::from),+ authentication+ .clone()+ .map(common_utils::pii::Email::from),webhook_url,&three_ds_connector_account,&authentication_connector.to_string(),@@ -1382,7 +1328,7 @@ pub async fn authentication_authenticate_core().await?;- let authentication = utils::external_authentication_update_trackers(+ let authentication = Box::pin(utils::external_authentication_update_trackers(&state,auth_response,authentication.clone(),@@ -1392,7 +1338,11 @@ pub async fn authentication_authenticate_core(None,None,None,- )+ req.sdk_information+ .and_then(|sdk_information| sdk_information.device_details),+ None,+ None,+ )).await?;let (authentication_value, eci) = match auth_flow {@@ -1676,7 +1626,7 @@ pub async fn authentication_retrieve_eligibility_check_core(implForeignTryFrom<(- &Authentication,+ &hyperswitch_domain_models::authentication::Authentication,Option<masking::Secret<String>>,Option<String>,diesel_models::business_profile::AuthenticationConnectorDetails,@@ -1686,7 +1636,7 @@ implfn foreign_try_from((authentication, authentication_value, eci, authentication_details): (- &Authentication,+ &hyperswitch_domain_models::authentication::Authentication,Option<masking::Secret<String>>,Option<String>,diesel_models::business_profile::AuthenticationConnectorDetails,@@ -1744,8 +1694,14 @@ pub async fn authentication_sync_core(let merchant_account = platform.get_processor().get_account();let merchant_id = merchant_account.get_id();let db = &*state.store;+ let key_manager_state = (&state).into();let authentication = db- .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)+ .find_authentication_by_merchant_id_authentication_id(+ merchant_id,+ &authentication_id,+ platform.get_processor().get_key_store(),+ &key_manager_state,+ ).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {id: authentication_id.get_string_repr().to_owned(),@@ -1760,8 +1716,6 @@ pub async fn authentication_sync_core(}).transpose()?;- let key_manager_state = (&state).into();-let profile_id = authentication.profile_id.clone();let business_profile = db@@ -1925,6 +1879,9 @@ pub async fn authentication_sync_core(None,None,None,+ None,+ None,+ None,).await?;@@ -1952,51 +1909,6 @@ pub async fn authentication_sync_core(merchant_country_code: updated_authentication.acquirer_country_code.clone(),});- let encrypted_data = domain::types::crypto_operation(- &key_manager_state,- common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication),- domain::types::CryptoOperation::BatchDecrypt(- hyperswitch_domain_models::authentication::EncryptedAuthentication::to_encryptable(- hyperswitch_domain_models::authentication::EncryptedAuthentication {- billing_address: updated_authentication.billing_address,- shipping_address: updated_authentication.shipping_address,- },- ),- ),- common_utils::types::keymanager::Identifier::Merchant(- platform.get_processor().get_key_store().merchant_id.clone(),- ),- platform.get_processor().get_key_store().key.peek(),- )- .await- .and_then(|val| val.try_into_batchoperation())- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt authentication data".to_string())?;-- let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Unable to get encrypted data for authentication after encryption")?;-- let email_decrypted = updated_authentication- .clone()- .async_lift(|inner| async {- domain::types::crypto_operation(- &key_manager_state,- common_utils::type_name!(Authentication),- domain::types::CryptoOperation::DecryptOptional(inner),- common_utils::types::keymanager::Identifier::Merchant(- platform.get_processor().get_key_store().merchant_id.clone(),- ),- platform.get_processor().get_key_store().key.peek(),- )- .await- .and_then(|val| val.try_into_optionaloperation())- })- .await- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt email")?;-let browser_info = updated_authentication.browser_info.clone()@@ -2022,7 +1934,7 @@ pub async fn authentication_sync_core(.change_context(ApiErrorResponse::InternalServerError).attach_printable("Incorrect authentication connector stored in table")?;- let billing = encrypted_data+ let billing = updated_authentication.billing_address.map(|billing| {billing@@ -2034,7 +1946,7 @@ pub async fn authentication_sync_core(.change_context(ApiErrorResponse::InternalServerError).attach_printable("Failed to parse billing address")?;- let shipping = encrypted_data+ let shipping = updated_authentication.shipping_address.map(|shipping| {shipping@@ -2077,7 +1989,7 @@ pub async fn authentication_sync_core(billing,shipping,browser_information: browser_info,- email: email_decrypted,+ email: updated_authentication.email,transaction_status: updated_authentication.trans_status.clone(),acs_url: updated_authentication.acs_url.clone(),challenge_request: updated_authentication.challenge_request.clone(),@@ -2109,8 +2021,14 @@ pub async fn authentication_post_sync_core(let merchant_account = platform.get_processor().get_account();let merchant_id = merchant_account.get_id();let db = &*state.store;+ let key_manager_state = (&state).into();let authentication = db- .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)+ .find_authentication_by_merchant_id_authentication_id(+ merchant_id,+ &authentication_id,+ platform.get_processor().get_key_store(),+ &key_manager_state,+ ).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {id: authentication_id.get_string_repr().to_owned(),@@ -2161,6 +2079,9 @@ pub async fn authentication_post_sync_core(None,None,None,+ None,+ None,+ None,).await?;@@ -2219,11 +2140,17 @@ pub async fn authentication_session_core() -> RouterResponse<api_models::authentication::AuthenticationSessionResponse> {let merchant_account = platform.get_processor().get_account();let merchant_id = merchant_account.get_id();+ let key_manager_state = (&state).into();let authentication_id = req.authentication_id;let authentication = state.store- .find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)+ .find_authentication_by_merchant_id_authentication_id(+ merchant_id,+ &authentication_id,+ platform.get_processor().get_key_store(),+ &key_manager_state,+ ).await.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {id: authentication_id.get_string_repr().to_owned(),@@ -2272,14 +2199,14 @@ pub async fn get_session_token_for_click_to_pay(merchant_id: &common_utils::id_type::MerchantId,platform: &domain::Platform,authentication_product_ids: common_types::payments::AuthenticationConnectorAccountMap,- authentication: &Authentication,+ authentication: &hyperswitch_domain_models::authentication::Authentication,) -> RouterResult<api_models::authentication::AuthenticationSessionToken> {let click_to_pay_mca_id = authentication_product_ids.get_click_to_pay_connector_account_id().change_context(ApiErrorResponse::MissingRequiredField {field_name: "authentication_product_ids",})?;- let key_manager_state = &(state).into();+ let key_manager_state = &state.into();let merchant_connector_account = state.storediff --git a/crates/router/src/core/unified_authentication_service/types.rs b/crates/router/src/core/unified_authentication_service/types.rsindex 69eac79069..da1db091f8 100644--- a/crates/router/src/core/unified_authentication_service/types.rs+++ b/crates/router/src/core/unified_authentication_service/types.rs@@ -85,7 +85,7 @@ pub trait UnifiedAuthenticationService {_currency: Option<common_enums::Currency>,_message_category: MessageCategory,_device_channel: payments::DeviceChannel,- _authentication: diesel_models::authentication::Authentication,+ _authentication: hyperswitch_domain_models::authentication::Authentication,_return_url: Option<String>,_sdk_information: Option<payments::SdkInformation>,_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,@@ -112,7 +112,7 @@ pub trait UnifiedAuthenticationService {_currency: Option<common_enums::Currency>,_message_category: MessageCategory,_device_channel: payments::DeviceChannel,- _authentication_data: diesel_models::authentication::Authentication,+ _authentication_data: hyperswitch_domain_models::authentication::Authentication,_return_url: Option<String>,_sdk_information: Option<payments::SdkInformation>,_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,@@ -131,7 +131,7 @@ pub trait UnifiedAuthenticationService {}fn get_post_authentication_request_data(- _authentication: Option<diesel_models::authentication::Authentication>,+ _authentication: Option<hyperswitch_domain_models::authentication::Authentication>,) -> RouterResult<UasPostAuthenticationRequestData> {Err(errors::ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason("post_authentication".to_string()),@@ -149,7 +149,7 @@ pub trait UnifiedAuthenticationService {_authentication_id: &common_utils::id_type::AuthenticationId,_payment_method: common_enums::PaymentMethod,_merchant_id: &common_utils::id_type::MerchantId,- _authentication: Option<&diesel_models::authentication::Authentication>,+ _authentication: Option<&hyperswitch_domain_models::authentication::Authentication>,) -> RouterResult<hyperswitch_domain_models::types::UasPostAuthenticationRouterData> {Err(errors::ApiErrorResponse::NotImplemented {message: NotImplementedMessage::Reason("post_authentication".to_string()),diff --git a/crates/router/src/core/unified_authentication_service/utils.rs b/crates/router/src/core/unified_authentication_service/utils.rsindex c7ef291265..0bd05cd9e9 100644--- a/crates/router/src/core/unified_authentication_service/utils.rs+++ b/crates/router/src/core/unified_authentication_service/utils.rs@@ -1,7 +1,12 @@use std::marker::PhantomData;+#[cfg(feature = "v1")]+use api_models::payments::BrowserInformation;use common_enums::enums::PaymentMethod;-use common_utils::ext_traits::{AsyncExt, ValueExt};+use common_utils::{+ ext_traits::{AsyncExt, ValueExt},+ types::keymanager::ToEncryptable,+};use error_stack::{report, ResultExt};use hyperswitch_domain_models::{business_profile,@@ -13,8 +18,9 @@ use hyperswitch_domain_models::{router_request_types::unified_authentication_service::{PostAuthenticationDetails, UasAuthenticationResponseData,},+ type_encryption::AsyncLift,};-use masking::ExposeInterface;+use masking::{ExposeInterface, PeekInterface};use super::types::{IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW,@@ -143,66 +149,162 @@ pub fn construct_uas_router_data<F: Clone, Req, Res>(}#[allow(clippy::too_many_arguments)]+#[cfg(feature = "v1")]pub async fn external_authentication_update_trackers<F: Clone, Req>(state: &SessionState,router_data: RouterData<F, Req, UasAuthenticationResponseData>,- authentication: diesel_models::authentication::Authentication,+ authentication: hyperswitch_domain_models::authentication::Authentication,acquirer_details: Option<hyperswitch_domain_models::router_request_types::authentication::AcquirerDetails,>,merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,- billing_address: Option<common_utils::encryption::Encryption>,- shipping_address: Option<common_utils::encryption::Encryption>,- email: Option<common_utils::encryption::Encryption>,- browser_info: Option<serde_json::Value>,-) -> RouterResult<diesel_models::authentication::Authentication> {+ billing_address: Option<hyperswitch_domain_models::address::Address>,+ shipping_address: Option<hyperswitch_domain_models::address::Address>,+ email: Option<common_utils::pii::Email>,+ browser_info: Option<BrowserInformation>,+ device_details: Option<api_models::payments::DeviceDetails>,+ merchant_category_code: Option<common_enums::MerchantCategoryCode>,+ merchant_country_code: Option<common_types::payments::MerchantCountryCode>,+) -> RouterResult<hyperswitch_domain_models::authentication::Authentication> {+ let key_state = state.into();let authentication_update = match router_data.response {Ok(response) => match response {UasAuthenticationResponseData::PreAuthentication {authentication_details,- } => Ok(- diesel_models::authentication::AuthenticationUpdate::PreAuthenticationUpdate {- threeds_server_transaction_id: authentication_details- .threeds_server_transaction_id- .ok_or(ApiErrorResponse::InternalServerError)- .attach_printable(- "missing threeds_server_transaction_id in PreAuthentication Details",- )?,- maximum_supported_3ds_version: authentication_details- .maximum_supported_3ds_version- .ok_or(ApiErrorResponse::InternalServerError)- .attach_printable(- "missing maximum_supported_3ds_version in PreAuthentication Details",- )?,- connector_authentication_id: authentication_details- .connector_authentication_id- .ok_or(ApiErrorResponse::InternalServerError)- .attach_printable(- "missing connector_authentication_id in PreAuthentication Details",- )?,- three_ds_method_data: authentication_details.three_ds_method_data,- three_ds_method_url: authentication_details.three_ds_method_url,- message_version: authentication_details- .message_version- .ok_or(ApiErrorResponse::InternalServerError)- .attach_printable("missing message_version in PreAuthentication Details")?,- connector_metadata: authentication_details.connector_metadata,- authentication_status: common_enums::AuthenticationStatus::Pending,- acquirer_bin: acquirer_details- .as_ref()- .map(|acquirer_details| acquirer_details.acquirer_bin.clone()),- acquirer_merchant_id: acquirer_details- .as_ref()- .map(|acquirer_details| acquirer_details.acquirer_merchant_id.clone()),- acquirer_country_code: acquirer_details- .and_then(|acquirer_details| acquirer_details.acquirer_country_code),- directory_server_id: authentication_details.directory_server_id,- browser_info: Box::new(browser_info),- email,- billing_address,- shipping_address,+ } => {+ let billing_details_encoded = billing_address+ .clone()+ .map(|billing| {+ common_utils::ext_traits::Encode::encode_to_value(&billing)+ .map(masking::Secret::<serde_json::Value>::new)+ })+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encode billing details to serde_json::Value")?;++ let shipping_details_encoded = shipping_address+ .clone()+ .map(|shipping| {+ common_utils::ext_traits::Encode::encode_to_value(&shipping)+ .map(masking::Secret::<serde_json::Value>::new)+ })+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encode shipping details to serde_json::Value")?;++ let encrypted_data = domain::types::crypto_operation(+ &key_state,+ common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication),+ domain::types::CryptoOperation::BatchEncrypt(+ hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication::to_encryptable(+ hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication {+ billing_address: billing_details_encoded,+ shipping_address: shipping_details_encoded,},),+ ),+ common_utils::types::keymanager::Identifier::Merchant(+ merchant_key_store+ .merchant_id+ .clone(),+ ),+ merchant_key_store.key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt authentication data".to_string())?;++ let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to get encrypted data for authentication after encryption")?;++ let email_encrypted = email+ .clone()+ .async_lift(|inner| async {+ domain::types::crypto_operation(+ &key_state,+ common_utils::type_name!(+ hyperswitch_domain_models::authentication::Authentication+ ),+ domain::types::CryptoOperation::EncryptOptional(+ inner.map(|inner| inner.expose()),+ ),+ common_utils::types::keymanager::Identifier::Merchant(+ merchant_key_store.merchant_id.clone(),+ ),+ merchant_key_store.key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt email")?;++ let browser_info = browser_info+ .as_ref()+ .map(common_utils::ext_traits::Encode::encode_to_value)+ .transpose()+ .change_context(ApiErrorResponse::InvalidDataValue {+ field_name: "browser_information",+ })?;+ Ok(+ hyperswitch_domain_models::authentication::AuthenticationUpdate::PreAuthenticationUpdate {+ earliest_supported_version:authentication_details.maximum_supported_3ds_version.clone(),+ latest_supported_version: authentication_details.maximum_supported_3ds_version.clone(),+ threeds_server_transaction_id: authentication_details+ .threeds_server_transaction_id+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "missing threeds_server_transaction_id in PreAuthentication Details",+ )?,+ maximum_supported_3ds_version: authentication_details+ .maximum_supported_3ds_version+ .clone()+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "missing maximum_supported_3ds_version in PreAuthentication Details",+ )?,+ connector_authentication_id: authentication_details+ .connector_authentication_id+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable(+ "missing connector_authentication_id in PreAuthentication Details",+ )?,+ three_ds_method_data: authentication_details.three_ds_method_data,+ three_ds_method_url: authentication_details.three_ds_method_url,+ message_version: authentication_details+ .message_version+ .ok_or(ApiErrorResponse::InternalServerError)+ .attach_printable("missing message_version in PreAuthentication Details")?,+ connector_metadata: authentication_details.connector_metadata.clone(),+ authentication_status: common_enums::AuthenticationStatus::Pending,+ acquirer_bin: acquirer_details+ .as_ref()+ .map(|acquirer_details| acquirer_details.acquirer_bin.clone()),+ acquirer_merchant_id: acquirer_details+ .as_ref()+ .map(|acquirer_details| acquirer_details.acquirer_merchant_id.clone()),+ acquirer_country_code: acquirer_details+ .and_then(|acquirer_details| acquirer_details.acquirer_country_code),+ directory_server_id: authentication_details.directory_server_id.clone(),+ browser_info: Box::new(browser_info),+ email:email_encrypted,+ billing_address: Box::new(encrypted_data.billing_address),+ shipping_address: Box::new(encrypted_data.shipping_address),+ scheme_id: authentication_details.scheme_id.clone(),+ merchant_category_code,+ merchant_country_code: merchant_country_code.map(|merchant_country_code| merchant_country_code.get_country_code()),+ billing_country: billing_address+ .clone()+ .and_then(|billing| billing.address.clone().and_then(|address| address.country.map(|country| country.to_string()))),+ shipping_country: shipping_address+ .clone()+ .and_then(|shipping| shipping.address.clone().and_then(|address| address.country.map(|country| country.to_string()))),+ },+ )+ }UasAuthenticationResponseData::Authentication {authentication_details,} => {@@ -226,7 +328,7 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(.await.transpose()?;Ok(- diesel_models::authentication::AuthenticationUpdate::AuthenticationUpdate {+ hyperswitch_domain_models::authentication::AuthenticationUpdate::AuthenticationUpdate {trans_status: authentication_details.trans_status,acs_url: authentication_details.authn_flow_type.get_acs_url(),challenge_request: authentication_details@@ -253,6 +355,18 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(challenge_cancel: authentication_details.challenge_cancel,challenge_code_reason: authentication_details.challenge_code_reason,message_extension: authentication_details.message_extension,+ device_type: device_details+ .as_ref()+ .and_then(|details| details.device_type.clone()),+ device_brand: device_details+ .as_ref()+ .and_then(|details| details.device_brand.clone()),+ device_os: device_details+ .as_ref()+ .and_then(|details| details.device_os.clone()),+ device_display: device_details+ .as_ref()+ .and_then(|details| details.device_display.clone()),},)}@@ -283,7 +397,7 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(.await.transpose()?;Ok(- diesel_models::authentication::AuthenticationUpdate::PostAuthenticationUpdate {+ hyperswitch_domain_models::authentication::AuthenticationUpdate::PostAuthenticationUpdate {authentication_status: common_enums::AuthenticationStatus::foreign_from(trans_status.clone(),),@@ -301,7 +415,7 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(.attach_printable("unexpected api confirmation in external authentication flow."),},Err(error) => Ok(- diesel_models::authentication::AuthenticationUpdate::ErrorUpdate {+ hyperswitch_domain_models::authentication::AuthenticationUpdate::ErrorUpdate {connector_authentication_id: error.connector_transaction_id,authentication_status: common_enums::AuthenticationStatus::Failed,error_message: error@@ -318,6 +432,8 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(.update_authentication_by_merchant_id_authentication_id(authentication,authentication_update,+ merchant_key_store,+ &key_state,).await.change_context(ApiErrorResponse::InternalServerError)@@ -341,7 +457,7 @@ pub fn get_checkout_event_status_and_reason(pub fn authenticate_authentication_client_secret_and_check_expiry(req_client_secret: &String,- authentication: &diesel_models::authentication::Authentication,+ authentication: &hyperswitch_domain_models::authentication::Authentication,) -> RouterResult<()> {let stored_client_secret = authentication.authentication_client_secretdiff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex ce8b3a1f7a..c14ebb5aa6 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -2167,12 +2167,13 @@ async fn external_authentication_incoming_webhook_flow(business_profile: domain::Profile,merchant_connector_account: domain::MerchantConnectorAccount,) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {+ let key_manager_state = (&state).into();if source_verified {let authentication_details = connector.get_external_authentication_details(request_details).switch()?;let trans_status = authentication_details.trans_status;- let authentication_update = storage::AuthenticationUpdate::PostAuthenticationUpdate {+ let authentication_update = hyperswitch_domain_models::authentication::AuthenticationUpdate::PostAuthenticationUpdate {authentication_status: common_enums::AuthenticationStatus::foreign_from(trans_status.clone(),),@@ -2191,6 +2192,8 @@ async fn external_authentication_incoming_webhook_flow(.find_authentication_by_merchant_id_authentication_id(platform.get_processor().get_account().get_id(),&authentication_id,+ platform.get_processor().get_key_store(),+ &key_manager_state,).await.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {@@ -2204,6 +2207,8 @@ async fn external_authentication_incoming_webhook_flow(.find_authentication_by_merchant_id_connector_authentication_id(platform.get_processor().get_account().get_id().clone(),connector_authentication_id.clone(),+ platform.get_processor().get_key_store(),+ &key_manager_state,).await.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {@@ -2221,6 +2226,8 @@ async fn external_authentication_incoming_webhook_flow(.update_authentication_by_merchant_id_authentication_id(authentication,authentication_update,+ platform.get_processor().get_key_store(),+ &key_manager_state,).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/db/authentication.rs b/crates/router/src/db/authentication.rsindex 74a309b7fb..c78d1309b7 100644--- a/crates/router/src/db/authentication.rs+++ b/crates/router/src/db/authentication.rs@@ -1,38 +1,47 @@-use diesel_models::authentication::AuthenticationUpdateInternal;-use error_stack::report;+use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState};+use error_stack::{report, ResultExt};+use hyperswitch_domain_models::{+ behaviour::{Conversion, ReverseConversion},+ merchant_key_store::MerchantKeyStore,+};use router_env::{instrument, tracing};+use storage_impl::StorageError;use super::{MockDb, Store};-use crate::{- connection,- core::errors::{self, CustomResult},- types::storage,-};+use crate::{connection, core::errors::CustomResult, types::storage};#[async_trait::async_trait]pub trait AuthenticationInterface {async fn insert_authentication(&self,- authentication: storage::AuthenticationNew,- ) -> CustomResult<storage::Authentication, errors::StorageError>;+ 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,- ) -> CustomResult<storage::Authentication, errors::StorageError>;+ 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,- ) -> CustomResult<storage::Authentication, errors::StorageError>;+ 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: storage::Authentication,- authentication_update: storage::AuthenticationUpdate,- ) -> CustomResult<storage::Authentication, errors::StorageError>;+ 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]@@ -40,13 +49,26 @@ impl AuthenticationInterface for Store {#[instrument(skip_all)]async fn insert_authentication(&self,- authentication: storage::AuthenticationNew,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ 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!(errors::StorageError::from(error)))+ .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)]@@ -54,7 +76,9 @@ impl AuthenticationInterface for Store {&self,merchant_id: &common_utils::id_type::MerchantId,authentication_id: &common_utils::id_type::AuthenticationId,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ 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,@@ -62,14 +86,28 @@ impl AuthenticationInterface for Store {authentication_id,).await- .map_err(|error| report!(errors::StorageError::from(error)))+ .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,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ 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,@@ -77,24 +115,48 @@ impl AuthenticationInterface for Store {&connector_authentication_id,).await- .map_err(|error| report!(errors::StorageError::from(error)))+ .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: storage::Authentication,- authentication_update: storage::AuthenticationUpdate,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ 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,+ authentication_update.into(),).await- .map_err(|error| report!(errors::StorageError::from(error)))+ .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}}@@ -102,13 +164,15 @@ impl AuthenticationInterface for Store {impl AuthenticationInterface for MockDb {async fn insert_authentication(&self,- authentication: storage::AuthenticationNew,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ 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(errors::StorageError::DuplicateValue {+ Err(StorageError::DuplicateValue {entity: "authentication_id",key: Some(authentication@@ -118,7 +182,7 @@ impl AuthenticationInterface for MockDb {),})?}- let authentication = storage::Authentication {+ let authentication_new = storage::Authentication {created_at: common_utils::date_time::now(),modified_at: common_utils::date_time::now(),authentication_id: authentication.authentication_id,@@ -164,17 +228,46 @@ impl AuthenticationInterface for MockDb {return_url: authentication.return_url,amount: authentication.amount,currency: authentication.currency,- billing_address: authentication.billing_address,- shipping_address: authentication.shipping_address,+ billing_address: None,+ shipping_address: None,browser_info: authentication.browser_info,- email: authentication.email,+ 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,};++ 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)}@@ -183,49 +276,231 @@ impl AuthenticationInterface for MockDb {&self,merchant_id: &common_utils::id_type::MerchantId,authentication_id: &common_utils::id_type::AuthenticationId,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ _merchant_key_store: &MerchantKeyStore,+ _state: &KeyManagerState,+ ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {let authentications = self.authentications.lock().await;+authentications.iter()- .find(|a| a.merchant_id == *merchant_id && a.authentication_id == *authentication_id)+ .find(|auth| {+ auth.merchant_id == *merchant_id && auth.authentication_id == *authentication_id+ })+ .cloned().ok_or(- errors::StorageError::ValueNotFound(format!(- "cannot find authentication for authentication_id = {authentication_id:?} and merchant_id = {merchant_id:?}"- )).into(),- ).cloned()+ 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,- ) -> CustomResult<storage::Authentication, errors::StorageError> {- Err(errors::StorageError::MockDbError)?+ 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: storage::Authentication,- authentication_update: storage::AuthenticationUpdate,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ 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 authentication_id = previous_state.authentication_id.clone();- let merchant_id = previous_state.merchant_id.clone();- authentications++ let auth_to_update = authentications.iter_mut()- .find(|authentication| authentication.authentication_id == authentication_id && authentication.merchant_id == merchant_id)- .map(|authentication| {- let authentication_update_internal =- AuthenticationUpdateInternal::from(authentication_update);- let updated_authentication = authentication_update_internal.apply_changeset(previous_state);- *authentication = updated_authentication.clone();- updated_authentication+ .find(|auth| {+ auth.merchant_id == previous_state.merchant_id+ && auth.authentication_id == previous_state.authentication_id})- .ok_or(- errors::StorageError::ValueNotFound(format!(- "cannot find authentication for authentication_id = {authentication_id:?} and merchant_id = {merchant_id:?}"- ))- .into(),- )+ .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;+ }+ }++ auth_to_update.modified_at = common_utils::date_time::now();++ Ok(auth_to_update.clone())}}diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex c72986ef17..bee4fbf67a 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -3774,11 +3774,14 @@ impl AuthorizationInterface for KafkaStore {impl AuthenticationInterface for KafkaStore {async fn insert_authentication(&self,- authentication: storage::AuthenticationNew,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ state: &KeyManagerState,+ key_store: &domain::MerchantKeyStore,+ authentication: hyperswitch_domain_models::authentication::Authentication,+ ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, errors::StorageError>+ {let auth = self.diesel_store- .insert_authentication(authentication)+ .insert_authentication(state, key_store, authentication).await?;if let Err(er) = self@@ -3796,9 +3799,17 @@ impl AuthenticationInterface for KafkaStore {&self,merchant_id: &id_type::MerchantId,authentication_id: &id_type::AuthenticationId,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ key_store: &domain::MerchantKeyStore,+ state: &KeyManagerState,+ ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, errors::StorageError>+ {self.diesel_store- .find_authentication_by_merchant_id_authentication_id(merchant_id, authentication_id)+ .find_authentication_by_merchant_id_authentication_id(+ merchant_id,+ authentication_id,+ key_store,+ state,+ ).await}@@ -3806,25 +3817,35 @@ impl AuthenticationInterface for KafkaStore {&self,merchant_id: id_type::MerchantId,connector_authentication_id: String,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ key_store: &domain::MerchantKeyStore,+ state: &KeyManagerState,+ ) -> CustomResult<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,).await}async fn update_authentication_by_merchant_id_authentication_id(&self,- previous_state: storage::Authentication,- authentication_update: storage::AuthenticationUpdate,- ) -> CustomResult<storage::Authentication, errors::StorageError> {+ previous_state: hyperswitch_domain_models::authentication::Authentication,+ authentication_update: hyperswitch_domain_models::authentication::AuthenticationUpdate,+ key_store: &domain::MerchantKeyStore,+ state: &KeyManagerState,+ ) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, errors::StorageError>+ {let auth = self.diesel_store.update_authentication_by_merchant_id_authentication_id(previous_state.clone(),authentication_update,+ key_store,+ state,).await?;diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 759504ee75..dedce6c807 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -3174,7 +3174,8 @@ impl Authentication {).service(web::resource("{merchant_id}/{authentication_id}/redirect")- .route(web::post().to(authentication::authentication_sync_post_update)),+ .route(web::post().to(authentication::authentication_sync_post_update))+ .route(web::get().to(authentication::authentication_sync_post_update)),).service(web::resource("{merchant_id}/{authentication_id}/sync")diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rsindex c724016abe..f8f81d72ba 100644--- a/crates/router/src/services/kafka.rs+++ b/crates/router/src/services/kafka.rs@@ -28,7 +28,7 @@ mod payment_intent_event;mod refund;mod refund_event;pub mod revenue_recovery;-use diesel_models::{authentication::Authentication, refund::Refund};+use diesel_models::refund::Refund;use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};use serde::Serialize;use time::{OffsetDateTime, PrimitiveDateTime};@@ -438,8 +438,8 @@ impl KafkaProducer {pub async fn log_authentication(&self,- authentication: &Authentication,- old_authentication: Option<Authentication>,+ authentication: &hyperswitch_domain_models::authentication::Authentication,+ old_authentication: Option<hyperswitch_domain_models::authentication::Authentication>,tenant_id: TenantID,) -> MQResult<()> {if let Some(negative_event) = old_authentication {diff --git a/crates/router/src/services/kafka/authentication.rs b/crates/router/src/services/kafka/authentication.rsindex 7d59e7e7dc..04d801038f 100644--- a/crates/router/src/services/kafka/authentication.rs+++ b/crates/router/src/services/kafka/authentication.rs@@ -1,4 +1,6 @@-use diesel_models::{authentication::Authentication, enums as storage_enums};+use api_models::payments::DeviceChannel;+use common_enums::MerchantCategoryCode;+use diesel_models::enums as storage_enums;use time::OffsetDateTime;#[derive(serde::Serialize, Debug)]@@ -42,10 +44,32 @@ pub struct KafkaAuthentication<'a> {pub directory_server_id: Option<&'a String>,pub acquirer_country_code: Option<&'a String>,pub organization_id: &'a common_utils::id_type::OrganizationId,+ pub platform: Option<&'a DeviceChannel>,+ pub mcc: Option<&'a MerchantCategoryCode>,+ pub currency: Option<&'a common_enums::Currency>,+ pub amount: Option<&'a common_utils::types::MinorUnit>,+ pub merchant_country: Option<&'a String>,+ pub billing_country: Option<&'a String>,+ pub shipping_country: Option<&'a String>,+ pub issuer_country: Option<&'a String>,+ pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub latest_supported_version: Option<common_utils::types::SemanticVersion>,+ pub device_type: Option<&'a String>,+ pub device_brand: Option<&'a String>,+ pub device_os: Option<&'a String>,+ pub device_display: Option<&'a String>,+ pub browser_name: Option<&'a String>,+ pub browser_version: Option<&'a String>,+ pub issuer_id: Option<&'a String>,+ pub scheme_name: Option<&'a String>,+ pub exemption_requested: Option<bool>,+ pub exemption_accepted: Option<bool>,}impl<'a> KafkaAuthentication<'a> {- pub fn from_storage(authentication: &'a Authentication) -> Self {+ pub fn from_storage(+ authentication: &'a hyperswitch_domain_models::authentication::Authentication,+ ) -> Self {Self {created_at: authentication.created_at.assume_utc(),modified_at: authentication.modified_at.assume_utc(),@@ -84,6 +108,26 @@ impl<'a> KafkaAuthentication<'a> {directory_server_id: authentication.directory_server_id.as_ref(),acquirer_country_code: authentication.acquirer_country_code.as_ref(),organization_id: &authentication.organization_id,+ platform: authentication.platform.as_ref(),+ mcc: authentication.mcc.as_ref(),+ currency: authentication.currency.as_ref(),+ amount: authentication.amount.as_ref(),+ merchant_country: authentication.merchant_country_code.as_ref(),+ billing_country: authentication.billing_country.as_ref(),+ shipping_country: authentication.shipping_country.as_ref(),+ issuer_country: authentication.issuer_country.as_ref(),+ earliest_supported_version: authentication.earliest_supported_version.clone(),+ latest_supported_version: authentication.latest_supported_version.clone(),+ device_type: authentication.device_type.as_ref(),+ device_brand: authentication.device_brand.as_ref(),+ device_os: authentication.device_os.as_ref(),+ device_display: authentication.device_display.as_ref(),+ browser_name: authentication.browser_name.as_ref(),+ browser_version: authentication.browser_version.as_ref(),+ issuer_id: authentication.issuer_id.as_ref(),+ scheme_name: authentication.scheme_name.as_ref(),+ exemption_requested: authentication.exemption_requested,+ exemption_accepted: authentication.exemption_accepted,}}}diff --git a/crates/router/src/services/kafka/authentication_event.rs b/crates/router/src/services/kafka/authentication_event.rsindex 796f1669d1..9ea95d8380 100644--- a/crates/router/src/services/kafka/authentication_event.rs+++ b/crates/router/src/services/kafka/authentication_event.rs@@ -1,4 +1,4 @@-use diesel_models::{authentication::Authentication, enums as storage_enums};+use diesel_models::enums as storage_enums;use time::OffsetDateTime;#[serde_with::skip_serializing_none]@@ -46,7 +46,9 @@ pub struct KafkaAuthenticationEvent<'a> {}impl<'a> KafkaAuthenticationEvent<'a> {- pub fn from_storage(authentication: &'a Authentication) -> Self {+ pub fn from_storage(+ authentication: &'a hyperswitch_domain_models::authentication::Authentication,+ ) -> Self {Self {created_at: authentication.created_at.assume_utc(),modified_at: authentication.modified_at.assume_utc(),diff --git a/crates/router/src/types/api/authentication.rs b/crates/router/src/types/api/authentication.rsindex 3322424ed4..118d3178c2 100644--- a/crates/router/src/types/api/authentication.rs+++ b/crates/router/src/types/api/authentication.rs@@ -10,10 +10,7 @@ pub use hyperswitch_domain_models::{router_request_types::authentication::MessageCategory,};-use crate::{- connector, core::errors, services::connector_integration_interface::ConnectorEnum,- types::storage,-};+use crate::{connector, core::errors, services::connector_integration_interface::ConnectorEnum};#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]pub struct AcquirerDetails {@@ -32,12 +29,17 @@ pub struct AuthenticationResponse {pub acs_trans_id: Option<String>,pub three_dsserver_trans_id: Option<String>,pub acs_signed_content: Option<String>,+ pub error_message: Option<String>,}-impl TryFrom<storage::Authentication> for AuthenticationResponse {+impl TryFrom<hyperswitch_domain_models::authentication::Authentication> for AuthenticationResponse {type Error = error_stack::Report<errors::ApiErrorResponse>;- fn try_from(authentication: storage::Authentication) -> Result<Self, Self::Error> {- let trans_status = authentication.trans_status.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("trans_status must be populated in authentication table authentication call is successful")?;+ fn try_from(+ authentication: hyperswitch_domain_models::authentication::Authentication,+ ) -> Result<Self, Self::Error> {+ let trans_status = authentication+ .trans_status+ .unwrap_or(common_enums::TransactionStatus::Failure);let acs_url = authentication.acs_url.map(|url| url::Url::from_str(&url))@@ -53,6 +55,7 @@ impl TryFrom<storage::Authentication> for AuthenticationResponse {three_dsserver_trans_id: authentication.threeds_server_transaction_id,acs_signed_content: authentication.acs_signed_content,challenge_request_key: authentication.challenge_request_key,+ error_message: authentication.error_message,})}}diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex 6d1c30437a..253d1c4a40 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -321,6 +321,8 @@ pub async fn find_mca_from_authentication_id_type(.find_authentication_by_merchant_id_authentication_id(platform.get_processor().get_account().get_id(),&authentication_id,+ platform.get_processor().get_key_store(),+ &state.into(),).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?,@@ -328,6 +330,8 @@ pub async fn find_mca_from_authentication_id_type(db.find_authentication_by_merchant_id_connector_authentication_id(platform.get_processor().get_account().get_id().clone(),connector_authentication_id,+ platform.get_processor().get_key_store(),+ &state.into(),).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rsindex 3832211d2c..3341bfad8a 100644--- a/crates/storage_impl/src/mock_db.rs+++ b/crates/storage_impl/src/mock_db.rs@@ -59,7 +59,7 @@ pub struct MockDb {pub payout_attempt: Arc<Mutex<Vec<store::payout_attempt::PayoutAttempt>>>,#[cfg(feature = "payouts")]pub payouts: Arc<Mutex<Vec<store::payouts::Payouts>>>,- pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>,+ pub authentications: Arc<Mutex<Vec<hyperswitch_domain_models::authentication::Authentication>>>,pub roles: Arc<Mutex<Vec<store::role::Role>>>,pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>,pub user_authentication_methods:diff --git a/migrations/2025-11-26-112831_add-authentication-analytics-related-fields-in-authentication-table/down.sql b/migrations/2025-11-26-112831_add-authentication-analytics-related-fields-in-authentication-table/down.sqlnew file mode 100644index 0000000000..9e041b0e78--- /dev/null+++ b/migrations/2025-11-26-112831_add-authentication-analytics-related-fields-in-authentication-table/down.sql@@ -0,0 +1,20 @@+-- This file should undo anything in `up.sql`+ALTER TABLE authentication+DROP COLUMN IF EXISTS earliest_supported_version,+DROP COLUMN IF EXISTS latest_supported_version,+DROP COLUMN IF EXISTS mcc,+DROP COLUMN IF EXISTS platform,+DROP COLUMN IF EXISTS device_type,+DROP COLUMN IF EXISTS device_brand,+DROP COLUMN IF EXISTS device_os,+DROP COLUMN IF EXISTS device_display,+DROP COLUMN IF EXISTS browser_name,+DROP COLUMN IF EXISTS browser_version,+DROP COLUMN IF EXISTS scheme_name,+DROP COLUMN IF EXISTS exemption_requested,+DROP COLUMN IF EXISTS exemption_accepted,+DROP COLUMN IF EXISTS issuer_id,+DROP COLUMN IF EXISTS issuer_country,+DROP COLUMN IF EXISTS merchant_country_code,+DROP COLUMN IF EXISTS billing_country,+DROP COLUMN IF EXISTS shipping_country;diff --git a/migrations/2025-11-26-112831_add-authentication-analytics-related-fields-in-authentication-table/up.sql b/migrations/2025-11-26-112831_add-authentication-analytics-related-fields-in-authentication-table/up.sqlnew file mode 100644index 0000000000..33c90215cc--- /dev/null+++ b/migrations/2025-11-26-112831_add-authentication-analytics-related-fields-in-authentication-table/up.sql@@ -0,0 +1,20 @@+-- Your SQL goes here+ALTER TABLE authentication+ADD COLUMN IF NOT EXISTS earliest_supported_version JSONB,+ADD COLUMN IF NOT EXISTS latest_supported_version JSONB,+ADD COLUMN IF NOT EXISTS mcc VARCHAR(8),+ADD COLUMN IF NOT EXISTS platform VARCHAR(64),+ADD COLUMN IF NOT EXISTS device_type VARCHAR(255),+ADD COLUMN IF NOT EXISTS device_brand VARCHAR(255),+ADD COLUMN IF NOT EXISTS device_os VARCHAR(255),+ADD COLUMN IF NOT EXISTS device_display VARCHAR(255),+ADD COLUMN IF NOT EXISTS browser_name VARCHAR(255),+ADD COLUMN IF NOT EXISTS browser_version VARCHAR(255),+ADD COLUMN IF NOT EXISTS scheme_name VARCHAR(255),+ADD COLUMN IF NOT EXISTS exemption_requested BOOLEAN,+ADD COLUMN IF NOT EXISTS exemption_accepted BOOLEAN,+ADD COLUMN IF NOT EXISTS issuer_id VARCHAR(255),+ADD COLUMN IF NOT EXISTS issuer_country VARCHAR(16),+ADD COLUMN IF NOT EXISTS merchant_country_code VARCHAR(8),+ADD COLUMN IF NOT EXISTS billing_country VARCHAR(16),+ADD COLUMN IF NOT EXISTS shipping_country VARCHAR(16);\ No newline at end of file