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 modular authentication as service (#12277)
Sahkal Poddar3ec9b0b11782
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.tomlindex 991537291c..9b835071cd 100644--- a/config/deployments/integration_test.toml+++ b/config/deployments/integration_test.toml@@ -1044,3 +1044,6 @@ ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated list"29" = { description = "Retry after 8 days", recommended_action = "retry_after_8_days" }"30" = { description = "Retry after 10 days", recommended_action = "retry_after_10_days" }+[micro_services.authentication_service]+base_url = "http://localhost:8080"+api_key = "api-key"\ No newline at end of filediff --git a/config/deployments/production.toml b/config/deployments/production.tomlindex 0b1d13aa36..08224fbc10 100644--- a/config/deployments/production.toml+++ b/config/deployments/production.toml@@ -1051,3 +1051,7 @@ ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated list"28" = { description = "Retry after 6 days", recommended_action = "retry_after_6_days" }"29" = { description = "Retry after 8 days", recommended_action = "retry_after_8_days" }"30" = { description = "Retry after 10 days", recommended_action = "retry_after_10_days" }++[micro_services.authentication_service]+base_url = "https://api.hyperswitch.io"+api_key = "api-key"\ No newline at end of filediff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.tomlindex 334e5b3092..e45cbded53 100644--- a/config/deployments/sandbox.toml+++ b/config/deployments/sandbox.toml@@ -1062,3 +1062,7 @@ ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated list"28" = { description = "Retry after 6 days", recommended_action = "retry_after_6_days" }"29" = { description = "Retry after 8 days", recommended_action = "retry_after_8_days" }"30" = { description = "Retry after 10 days", recommended_action = "retry_after_10_days" }++[micro_services.authentication_service]+base_url = "http://localhost:8080"+api_key = "api-key"\ No newline at end of filediff --git a/config/development.toml b/config/development.tomlindex 77791380f0..4ac1bcefcb 100644--- a/config/development.toml+++ b/config/development.toml@@ -1566,4 +1566,8 @@ backup_file_path = "./config/superposition_seed.toml" # Path to a local file for[micro_services]payment_methods_base_url = "http://localhost:8082"payment_methods_prefix = "v2"-use_legacy_locker = false\ No newline at end of file+use_legacy_locker = false++[micro_services.authentication_service]+base_url = "http://localhost:8080"+api_key = "api-key"\ No newline at end of filediff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex a6ff64a8c9..12f9f9fe54 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -1440,3 +1440,7 @@ backup_file_path = "./config/superposition_seed.toml" # Path to a local file for"28" = { description = "Retry after 6 days", recommended_action = "retry_after_6_days" }"29" = { description = "Retry after 8 days", recommended_action = "retry_after_8_days" }"30" = { description = "Retry after 10 days", recommended_action = "retry_after_10_days" }++[micro_services.authentication_service]+base_url = "http://localhost:8080"+api_key = "api-key"\ No newline at end of filediff --git a/crates/api_models/src/authentication.rs b/crates/api_models/src/authentication.rsindex 1fde17314b..ac7b1094fb 100644--- a/crates/api_models/src/authentication.rs+++ b/crates/api_models/src/authentication.rs@@ -202,7 +202,7 @@ impl ApiEventMetric for AuthenticationRetrieveEligibilityCheckResponse {}#[cfg(feature = "v1")]-#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct AuthenticationEligibilityRequest {/// Payment method-specific data such as card details, wallet info, etc./// This holds the raw information required to process the payment method.@@ -277,7 +277,7 @@ impl AuthenticationEligibilityRequest {}#[cfg(feature = "v1")]-#[derive(Debug, Serialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct AuthenticationEligibilityResponse {/// The unique identifier for this authentication.#[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")]@@ -323,6 +323,21 @@ pub struct AuthenticationEligibilityResponse {pub acquirer_details: Option<AcquirerDetails>,}+#[cfg(feature = "v1")]+impl AuthenticationEligibilityResponse {+ pub fn is_separate_authn_required(&self) -> bool {+ match &self.eligibility_response_params {+ Some(params) => match params {+ EligibilityResponseParams::ThreeDsData(threeds) => threeds+ .maximum_supported_3ds_version+ .as_ref()+ .is_some_and(|version| version.get_major() == 2),+ },+ None => false,+ }+ }+}+#[cfg(feature = "v1")]#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct AuthenticationEligibilityCheckRequest {@@ -449,12 +464,12 @@ pub struct MasterCardEligibilityCheckData {pub last_used_card_timestamp: Option<String>,}-#[derive(Debug, Serialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub enum EligibilityResponseParams {ThreeDsData(ThreeDsData),}-#[derive(Debug, Serialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct ThreeDsData {/// The unique identifier for this authentication from the 3DS server.#[schema(value_type = String)]@@ -479,7 +494,7 @@ pub struct ThreeDsData {pub directory_server_id: Option<String>,}-#[derive(Debug, Serialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct NextAction {/// The URL for authenticatating the user.#[schema(value_type = String)]@@ -593,7 +608,7 @@ impl ApiEventMetric for AuthenticationAuthenticateResponse {}#[cfg(feature = "v1")]-#[derive(Debug, Clone, Serialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct AuthenticationSyncResponse {// Core Authentication Fields (from AuthenticationResponse)/// The unique identifier for this authentication.@@ -747,7 +762,7 @@ pub struct AuthenticationSyncResponse {pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>,}-#[derive(Debug, Clone, Serialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct AuthenticationDetails {// Three Ds Data after external authenticationpub three_ds_data: Option<ExternalThreeDsData>,@@ -785,7 +800,7 @@ pub enum Cryptogram {}#[cfg(feature = "v1")]-#[derive(Debug, Clone, Serialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]#[serde(tag = "type", rename_all = "snake_case")]pub enum AuthenticationPaymentMethodDataResponse {CardData {@@ -809,7 +824,7 @@ pub enum AuthenticationPaymentMethodDataResponse {}#[cfg(feature = "v1")]-#[derive(Debug, Clone, Serialize, ToSchema)]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]#[serde(tag = "type", rename_all = "snake_case")]pub enum AuthenticationVaultTokenData {CardData {diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rsindex cc4b8ef815..5354e436c2 100644--- a/crates/common_utils/src/crypto.rs+++ b/crates/common_utils/src/crypto.rs@@ -708,6 +708,22 @@ where}}+impl<'de, T: Clone> serde::Deserialize<'de> for Encryptable<T>+where+ T: serde::Deserialize<'de>,+{+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ let inner = T::deserialize(deserializer)?;+ Ok(Self {+ inner,+ encrypted: Secret::new(Vec::new()),+ })+ }+}+impl<T: Clone> PartialEq for Encryptable<T>whereT: PartialEq,diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rsindex 7f108b20a7..d62407f8c2 100644--- a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs@@ -195,3 +195,18 @@ pub struct AuthenticationInfo {pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,pub merchant_country_code: Option<common_enums::CountryAlpha2>,}++#[cfg(feature = "v1")]+impl From<api_models::authentication::AuthenticationEligibilityRequest> for AuthenticationInfo {+ fn from(req: api_models::authentication::AuthenticationEligibilityRequest) -> Self {+ Self {+ billing_address: req.billing.map(address::Address::from),+ shipping_address: req.shipping.map(address::Address::from),+ browser_info: req.browser_information.map(BrowserInformation::from),+ email: req.email,+ device_details: None,+ merchant_category_code: None,+ merchant_country_code: None,+ }+ }+}diff --git a/crates/hyperswitch_interfaces/src/micro_service/macros.rs b/crates/hyperswitch_interfaces/src/micro_service/macros.rsindex 8a50f4828f..39e7d0893e 100644--- a/crates/hyperswitch_interfaces/src/micro_service/macros.rs+++ b/crates/hyperswitch_interfaces/src/micro_service/macros.rs@@ -111,7 +111,7 @@ macro_rules! impl_microservice_flow {&self,request: Self::V2Request,) -> Option<common_utils::request::RequestContent> {- $body_fn(self, request)+ ($body_fn)(self, request)})?@@ -120,7 +120,7 @@ macro_rules! impl_microservice_flow {&self,request: &Self::V1Request,) -> Vec<(&'static str, String)> {- $path_params_fn(self, request)+ ($path_params_fn)(self, request)})?@@ -129,7 +129,7 @@ macro_rules! impl_microservice_flow {&self,request: &Self::V1Request,) -> Vec<(&'static str, String)> {- $query_params_fn(self, request)+ ($query_params_fn)(self, request)})?}diff --git a/crates/payment_methods/src/configs.rs b/crates/payment_methods/src/configs.rsindex eeb686c32d..8b198b2500 100644--- a/crates/payment_methods/src/configs.rs+++ b/crates/payment_methods/src/configs.rs@@ -1,6 +1,7 @@pub mod payment_connector_required_fields;pub mod settings;+use hyperswitch_masking::Secret;use serde::Deserialize;use url::Url;@@ -12,6 +13,44 @@ pub struct MicroServicesConfig {pub payment_methods_base_url: ModularPaymentMethodServiceUrl,pub payment_methods_prefix: ModularPaymentMethodServicePrefix,pub use_legacy_locker: bool,+ pub authentication_service: AuthenticationServiceConfig,+}++/// Configuration for the authentication microservice.+#[derive(Debug, Deserialize, Clone, Default)]+#[serde(default)]+pub struct AuthenticationServiceConfig {+ pub base_url: AuthenticationServiceUrl,+ pub api_key: Secret<String>,+}++/// Base URL wrapper for the modular payment methods service.+#[derive(Debug, Deserialize, Clone)]+#[serde(transparent)]+pub struct AuthenticationServiceUrl(pub Url);++impl Default for AuthenticationServiceUrl {+ fn default() -> Self {+ Self(+ #[allow(clippy::expect_used)]+ Url::parse("http://localhost:8080")+ .expect("Failed to parse default payment_methods_base_url"),+ )+ }+}++impl std::ops::Deref for AuthenticationServiceUrl {+ type Target = Url;++ fn deref(&self) -> &Self::Target {+ &self.0+ }+}++impl AsRef<Url> for AuthenticationServiceUrl {+ fn as_ref(&self) -> &Url {+ &self.0+ }}/// Prefix wrapper for the modular payment methods service.diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 48a087ecb1..2e073ec7a4 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -41,7 +41,7 @@ pub use payment_methods::configs::{PaymentMethodType, RequiredFieldFinal, RequiredFields, SupportedConnectorsForMandate,SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, ZeroMandates,},- MicroServicesConfig,+ AuthenticationServiceConfig, MicroServicesConfig,};use rand::seq::IteratorRandom;use redis_interface::RedisSettings;diff --git a/crates/router/src/core.rs b/crates/router/src/core.rsindex b6c13c54fc..55ec0f77be 100644--- a/crates/router/src/core.rs+++ b/crates/router/src/core.rs@@ -5,6 +5,8 @@ pub mod api_locking;pub mod apple_pay_certificates_migration;pub mod authentication;#[cfg(feature = "v1")]+pub mod authentication_client;+#[cfg(feature = "v1")]pub mod blocklist;pub mod cache;pub mod card_issuer;diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rsindex 260a012391..40b5fc48c3 100644--- a/crates/router/src/core/authentication/transformers.rs+++ b/crates/router/src/core/authentication/transformers.rs@@ -5,6 +5,7 @@ use common_enums::PaymentMethod;use common_utils::ext_traits::ValueExt;use error_stack::ResultExt;use hyperswitch_domain_models::authentication;+use hyperswitch_masking::ExposeInterface;use crate::{core::{@@ -234,3 +235,262 @@ impl ForeignFrom<common_enums::TransactionStatus> for common_enums::Authenticati}}}++pub fn construct_authentication_domain_model<T>(input: T) -> authentication::Authentication+where+ authentication::Authentication: ForeignFrom<T>,+{+ authentication::Authentication::foreign_from(input)+}++#[cfg(feature = "v1")]+impl+ ForeignFrom<(+ api_models::authentication::AuthenticationResponse,+ api_models::authentication::AuthenticationEligibilityResponse,+ Option<api_models::authentication::ThreeDsData>,+ common_utils::id_type::ProfileId,+ common_utils::id_type::OrganizationId,+ )> for authentication::Authentication+{+ fn foreign_from(+ (auth_create_response, elig_response, three_ds_data, profile_id, organization_id): (+ api_models::authentication::AuthenticationResponse,+ api_models::authentication::AuthenticationEligibilityResponse,+ Option<api_models::authentication::ThreeDsData>,+ common_utils::id_type::ProfileId,+ common_utils::id_type::OrganizationId,+ ),+ ) -> Self {+ Self {+ authentication_id: auth_create_response.authentication_id,+ merchant_id: auth_create_response.merchant_id,+ authentication_connector: auth_create_response+ .authentication_connector+ .map(|c| c.to_string()),+ connector_authentication_id: three_ds_data+ .as_ref()+ .and_then(|d| d.connector_authentication_id.clone()),+ authentication_data: None,+ payment_method_id: "".to_string(),+ authentication_type: None,+ authentication_status: auth_create_response.status,+ authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused,+ created_at: auth_create_response+ .created_at+ .unwrap_or_else(common_utils::date_time::now),+ modified_at: auth_create_response+ .created_at+ .unwrap_or_else(common_utils::date_time::now),+ error_message: auth_create_response.error_message,+ error_code: auth_create_response.error_code,+ connector_metadata: elig_response.connector_metadata,+ maximum_supported_version: three_ds_data+ .as_ref()+ .and_then(|d| d.maximum_supported_3ds_version.clone()),+ threeds_server_transaction_id: three_ds_data+ .as_ref()+ .and_then(|d| d.three_ds_server_transaction_id.clone()),+ cavv: None,+ authentication_flow_type: None,+ message_version: three_ds_data+ .as_ref()+ .and_then(|d| d.message_version.clone()),+ eci: None,+ trans_status: None,+ acquirer_bin: auth_create_response+ .acquirer_details+ .as_ref()+ .and_then(|a| a.acquirer_bin.clone()),+ acquirer_merchant_id: auth_create_response+ .acquirer_details+ .as_ref()+ .and_then(|a| a.acquirer_merchant_id.clone()),+ three_ds_method_data: three_ds_data+ .as_ref()+ .and_then(|d| d.three_ds_method_data.clone()),+ three_ds_method_url: three_ds_data+ .as_ref()+ .and_then(|d| d.three_ds_method_url.clone().map(|u| u.to_string())),+ acs_url: None,+ challenge_request: None,+ acs_reference_number: None,+ acs_trans_id: None,+ acs_signed_content: None,+ profile_id,+ payment_id: None,+ merchant_connector_id: None,+ ds_trans_id: None,+ directory_server_id: three_ds_data+ .as_ref()+ .and_then(|d| d.directory_server_id.clone()),+ acquirer_country_code: auth_create_response+ .acquirer_details+ .as_ref()+ .and_then(|a| a.merchant_country_code.clone()),+ organization_id,+ mcc: None,+ currency: Some(auth_create_response.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: None,+ exemption_accepted: None,+ service_details: None,+ authentication_client_secret: auth_create_response.client_secret.map(|s| s.expose()),+ force_3ds_challenge: auth_create_response.force_3ds_challenge,+ psd2_sca_exemption_type: auth_create_response.psd2_sca_exemption_type,+ return_url: auth_create_response.return_url,+ billing_address: None,+ shipping_address: None,+ browser_info: None,+ email: None,+ profile_acquirer_id: auth_create_response.profile_acquirer_id,+ challenge_code: None,+ challenge_cancel: None,+ challenge_code_reason: None,+ message_extension: None,+ challenge_request_key: None,+ customer_details: None,+ amount: Some(auth_create_response.amount),+ merchant_country_code: None,+ processor_merchant_id: None,+ created_by: None,+ }+ }+}++#[cfg(feature = "v1")]+impl+ ForeignFrom<(+ api_models::authentication::AuthenticationSyncResponse,+ common_utils::id_type::OrganizationId,+ )> for authentication::Authentication+{+ fn foreign_from(+ (sync_response, organization_id): (+ api_models::authentication::AuthenticationSyncResponse,+ common_utils::id_type::OrganizationId,+ ),+ ) -> Self {+ Self {+ authentication_id: sync_response.authentication_id,+ merchant_id: sync_response.merchant_id,+ authentication_connector: sync_response+ .authentication_connector+ .map(|c| c.to_string()),+ connector_authentication_id: sync_response.connector_authentication_id,+ authentication_data: None,+ payment_method_id: "".to_string(),+ authentication_type: None,+ authentication_status: sync_response.status,+ authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused,+ created_at: sync_response.created_at,+ modified_at: sync_response.created_at,+ error_message: None,+ error_code: None,+ connector_metadata: sync_response.connector_metadata,+ maximum_supported_version: sync_response.maximum_supported_3ds_version,+ threeds_server_transaction_id: sync_response.threeds_server_transaction_id,+ cavv: sync_response.authentication_details.as_ref().and_then(|d| {+ match &d.three_ds_data {+ Some(three_ds_data) => match &three_ds_data.authentication_cryptogram {+ Some(api_models::authentication::Cryptogram::Cavv {+ authentication_cryptogram,+ }) => Some(authentication_cryptogram.clone().expose()),+ _ => None,+ },+ None => None,+ }+ }),+ authentication_flow_type: None,+ message_version: sync_response.message_version,+ eci: sync_response+ .authentication_details+ .as_ref()+ .and_then(|d| d.three_ds_data.as_ref().and_then(|t| t.eci.clone())),+ trans_status: sync_response.authentication_details.as_ref().and_then(|d| {+ d.three_ds_data+ .as_ref()+ .map(|t| t.transaction_status.clone())+ }),+ acquirer_bin: sync_response+ .acquirer_details+ .as_ref()+ .and_then(|a| a.acquirer_bin.clone()),+ acquirer_merchant_id: sync_response+ .acquirer_details+ .as_ref()+ .and_then(|a| a.acquirer_merchant_id.clone()),+ three_ds_method_data: sync_response.three_ds_method_data,+ three_ds_method_url: sync_response.three_ds_method_url,+ acs_url: None,+ challenge_request: None,+ acs_reference_number: None,+ acs_trans_id: None,+ acs_signed_content: None,+ profile_id: sync_response.profile_id,+ payment_id: None,+ merchant_connector_id: None,+ ds_trans_id: sync_response+ .authentication_details+ .as_ref()+ .and_then(|d| d.three_ds_data.as_ref().and_then(|t| t.ds_trans_id.clone())),+ directory_server_id: sync_response.directory_server_id,+ acquirer_country_code: sync_response+ .acquirer_details+ .as_ref()+ .and_then(|a| a.merchant_country_code.clone()),+ organization_id,+ mcc: None,+ currency: Some(sync_response.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: None,+ exemption_accepted: None,+ service_details: None,+ authentication_client_secret: sync_response.client_secret.map(|s| s.expose()),+ force_3ds_challenge: sync_response.force_3ds_challenge,+ psd2_sca_exemption_type: sync_response.psd2_sca_exemption_type,+ return_url: sync_response.return_url,+ billing_address: None,+ shipping_address: None,+ browser_info: None,+ email: None,+ profile_acquirer_id: None,+ challenge_code: None,+ challenge_cancel: None,+ challenge_code_reason: None,+ message_extension: None,+ challenge_request_key: None,+ customer_details: None,+ amount: Some(sync_response.amount),+ merchant_country_code: None,+ processor_merchant_id: None,+ created_by: None,+ }+ }+}diff --git a/crates/router/src/core/authentication_client.rs b/crates/router/src/core/authentication_client.rsnew file mode 100644index 0000000000..8bba6cddc5--- /dev/null+++ b/crates/router/src/core/authentication_client.rs@@ -0,0 +1,236 @@+use api_models::authentication::{+ AuthenticationAuthenticateRequest, AuthenticationAuthenticateResponse,+ AuthenticationCreateRequest, AuthenticationEligibilityRequest,+ AuthenticationEligibilityResponse, AuthenticationResponse, AuthenticationSyncPostUpdateRequest,+ AuthenticationSyncRequest, AuthenticationSyncResponse,+};+use common_utils::request::{Headers, Method, RequestContent};+use hyperswitch_interfaces::{impl_microservice_flow, micro_service::MicroserviceClient};+use payment_methods::configs::AuthenticationServiceConfig;+use router_env::RequestIdentifier;+use serde::{Deserialize, Serialize};+use url::Url;++pub struct AuthenticationServiceClient<'a> {+ base_url: Url,+ parent_headers: Headers,+ trace: &'a RequestIdentifier,+}++impl<'a> AuthenticationServiceClient<'a> {+ pub fn new(+ config: &'a AuthenticationServiceConfig,+ trace: &'a RequestIdentifier,+ ) -> Result<Self, hyperswitch_interfaces::micro_service::MicroserviceClientError> {+ let base_url = config.base_url.0.clone();++ let mut parent_headers = Headers::new();+ parent_headers.insert((+ "api-key".to_string(),+ hyperswitch_masking::Maskable::new_masked(config.api_key.clone()),+ ));++ Ok(Self {+ base_url,+ parent_headers,+ trace,+ })+ }+}++impl<'a> MicroserviceClient for AuthenticationServiceClient<'a> {+ fn base_url(&self) -> &Url {+ &self.base_url+ }+ fn parent_headers(&self) -> &Headers {+ &self.parent_headers+ }+ fn trace(&self) -> &RequestIdentifier {+ self.trace+ }+}++// ----------------------------------------------------------------------------+// Flow: authentication_create+// ----------------------------------------------------------------------------+pub struct AuthenticationCreateFlow;++#[derive(Serialize)]+pub struct AuthCreateReq(pub AuthenticationCreateRequest);++#[derive(Deserialize)]+pub struct AuthCreateResp(pub AuthenticationResponse);++impl TryFrom<&AuthenticationCreateRequest> for AuthCreateReq {+ type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;+ fn try_from(req: &AuthenticationCreateRequest) -> Result<Self, Self::Error> {+ Ok(Self(req.clone()))+ }+}++impl TryFrom<AuthCreateResp> for AuthenticationResponse {+ type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;+ fn try_from(resp: AuthCreateResp) -> Result<Self, Self::Error> {+ Ok(resp.0)+ }+}++impl_microservice_flow!(+ AuthenticationCreateFlow,+ method = Method::Post,+ path = "/authentication",+ v1_request = AuthenticationCreateRequest,+ v2_request = AuthCreateReq,+ v2_response = AuthCreateResp,+ v1_response = AuthenticationResponse,+ client = AuthenticationServiceClient<'_>,+ body = |_, req: AuthCreateReq| Some(RequestContent::Json(Box::new(serde_json::json!(req.0))))+);++// ----------------------------------------------------------------------------+// Flow: authentication_eligibility+// ----------------------------------------------------------------------------+pub struct AuthenticationEligibilityFlow;++#[derive(Serialize)]+pub struct AuthEligibilityReq(pub AuthenticationEligibilityRequest);++#[derive(Deserialize)]+pub struct AuthEligibilityResp(pub AuthenticationEligibilityResponse);++impl TryFrom<&(AuthenticationEligibilityRequest, String)> for AuthEligibilityReq {+ type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;+ fn try_from(req: &(AuthenticationEligibilityRequest, String)) -> Result<Self, Self::Error> {+ Ok(Self(req.0.clone()))+ }+}++impl TryFrom<AuthEligibilityResp> for AuthenticationEligibilityResponse {+ type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;+ fn try_from(resp: AuthEligibilityResp) -> Result<Self, Self::Error> {+ Ok(resp.0)+ }+}++impl_microservice_flow!(+ AuthenticationEligibilityFlow,+ method = Method::Post,+ path = "/authentication/{authentication_id}/eligibility",+ v1_request = (AuthenticationEligibilityRequest, String), // passing auth_id separately for path+ v2_request = AuthEligibilityReq,+ v2_response = AuthEligibilityResp,+ v1_response = AuthenticationEligibilityResponse,+ client = AuthenticationServiceClient<'_>,+ body = |_, req: AuthEligibilityReq| Some(RequestContent::Json(Box::new(serde_json::json!(req.0)))),+ path_params = |_, req: &(AuthenticationEligibilityRequest, String)| vec![("authentication_id", req.1.clone())]+);++// ----------------------------------------------------------------------------+// Flow: authentication_authenticate+// ----------------------------------------------------------------------------+pub struct AuthenticationAuthenticateFlow;++#[derive(Serialize)]+pub struct AuthAuthenticateReq(pub AuthenticationAuthenticateRequest);++#[derive(Deserialize)]+pub struct AuthAuthenticateResp(pub AuthenticationAuthenticateResponse);++impl TryFrom<&AuthenticationAuthenticateRequest> for AuthAuthenticateReq {+ type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;+ fn try_from(req: &AuthenticationAuthenticateRequest) -> Result<Self, Self::Error> {+ Ok(Self(req.clone()))+ }+}++impl TryFrom<AuthAuthenticateResp> for AuthenticationAuthenticateResponse {+ type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;+ fn try_from(resp: AuthAuthenticateResp) -> Result<Self, Self::Error> {+ Ok(resp.0)+ }+}++impl_microservice_flow!(+ AuthenticationAuthenticateFlow,+ method = Method::Post,+ path = "/authentication/{authentication_id}/authenticate",+ v1_request = AuthenticationAuthenticateRequest,+ v2_request = AuthAuthenticateReq,+ v2_response = AuthAuthenticateResp,+ v1_response = AuthenticationAuthenticateResponse,+ client = AuthenticationServiceClient<'_>,+ body = |_, req: AuthAuthenticateReq| Some(RequestContent::Json(Box::new(serde_json::json!(req.0)))),+ path_params = |_, req: &AuthenticationAuthenticateRequest| vec![("authentication_id", req.authentication_id.clone().get_string_repr().to_owned())]+);++// ----------------------------------------------------------------------------+// Flow: authentication_sync_post_update+// ----------------------------------------------------------------------------+pub struct AuthenticationSyncPostUpdateFlow;++#[derive(Serialize)]+pub struct AuthSyncPostUpdateReq(pub AuthenticationSyncPostUpdateRequest);++#[derive(Deserialize)]+pub struct AuthSyncResp(pub AuthenticationSyncResponse);++impl TryFrom<&(AuthenticationSyncPostUpdateRequest, String)> for AuthSyncPostUpdateReq {+ type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;+ fn try_from(req: &(AuthenticationSyncPostUpdateRequest, String)) -> Result<Self, Self::Error> {+ Ok(Self(req.0.clone()))+ }+}++impl TryFrom<AuthSyncResp> for AuthenticationSyncResponse {+ type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;+ fn try_from(resp: AuthSyncResp) -> Result<Self, Self::Error> {+ Ok(resp.0)+ }+}++impl_microservice_flow!(+ AuthenticationSyncPostUpdateFlow,+ method = Method::Post,+ path = "/authentication/{merchant_id}/{authentication_id}/redirect",+ v1_request = (AuthenticationSyncPostUpdateRequest, String), // the String is merchant_id+ v2_request = AuthSyncPostUpdateReq,+ v2_response = AuthSyncResp,+ v1_response = AuthenticationSyncResponse,+ client = AuthenticationServiceClient<'_>,+ body = |_, req: AuthSyncPostUpdateReq| Some(RequestContent::Json(Box::new(serde_json::json!(req.0)))),+ path_params = |_, req: &(AuthenticationSyncPostUpdateRequest, String)| vec![+ ("merchant_id", req.1.clone()),+ ("authentication_id", req.0.authentication_id.clone().get_string_repr().to_owned())+ ]+);++// ----------------------------------------------------------------------------+// Flow: authentication_sync+// ----------------------------------------------------------------------------+pub struct AuthenticationSyncFlow;++#[derive(Serialize)]+pub struct AuthSyncReq(pub AuthenticationSyncRequest);++impl TryFrom<&(AuthenticationSyncRequest, String)> for AuthSyncReq {+ type Error = hyperswitch_interfaces::micro_service::MicroserviceClientError;+ fn try_from(req: &(AuthenticationSyncRequest, String)) -> Result<Self, Self::Error> {+ Ok(Self(req.0.clone()))+ }+}++impl_microservice_flow!(+ AuthenticationSyncFlow,+ method = Method::Post,+ path = "/authentication/{merchant_id}/{authentication_id}/sync",+ v1_request = (AuthenticationSyncRequest, String), // string is merchant_id+ v2_request = AuthSyncReq,+ v2_response = AuthSyncResp,+ v1_response = AuthenticationSyncResponse,+ client = AuthenticationServiceClient<'_>,+ body = |_, req: AuthSyncReq| Some(RequestContent::Json(Box::new(serde_json::json!(req.0)))),+ path_params = |_, req: &(AuthenticationSyncRequest, String)| vec![+ ("merchant_id", req.1.clone()),+ ("authentication_id", req.0.authentication_id.clone().get_string_repr().to_owned())+ ]+);diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex bb06d75192..329b36c436 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -170,7 +170,7 @@ use crate::{core::revenue_recovery::get_workflow_entries, db::storage::payment_m#[cfg(feature = "v1")]use crate::{core::{- authentication as authentication_core, unified_authentication_service::utils as uas_utils,+ authentication as authentication_core,unified_connector_service::update_gateway_system_in_feature_metadata,},types::{api::authentication, BrowserInformation},@@ -11629,25 +11629,8 @@ pub async fn payment_external_authentication<F: Clone + Sync>(platform: domain::Platform,req: api_models::payments::PaymentsExternalAuthenticationRequest,) -> RouterResponse<api_models::payments::PaymentsExternalAuthenticationResponse> {- use super::unified_authentication_service::types::ExternalAuthentication;- use crate::core::unified_authentication_service::{- types::UnifiedAuthenticationService, utils::external_authentication_update_trackers,- };-let db = &*state.store;let key_manager_state = &(&(state)).into();-- let dimensions = Dimensions::new()- .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())- .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())- .with_organization_id(- platform- .get_processor()- .get_account()- .organization_id- .clone(),- );-let processor_merchant_id = platform.get_processor().get_account().get_id();let storage_scheme = platform.get_processor().get_account().storage_scheme;let payment_id = req.payment_id;@@ -11750,21 +11733,6 @@ pub async fn payment_external_authentication<F: Clone + Sync>().await?;- let authentication = db- .find_authentication_by_merchant_id_authentication_id(- processor_merchant_id,- &payment_attempt- .authentication_id- .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)- .attach_printable("Error while fetching authentication record")?;-let business_profile = state.store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), profile_id)@@ -11822,49 +11790,68 @@ pub async fn payment_external_authentication<F: Clone + Sync>(if helpers::is_merchant_eligible_authentication_service(platform.get_processor(), &state).await?{- let routing_region = uas_utils::fetch_routing_region_for_uas(&state, &dimensions).await;- let auth_response =- <ExternalAuthentication as UnifiedAuthenticationService>::authentication(+ let authentication_id = payment_attempt+ .authentication_id+ .clone()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("missing authentication_id in payment_attempt")?;++ let auth_config = &state.conf.micro_services.authentication_service;++ let req_identifier = router_env::RequestIdentifier::new("x-request-id");+ let client = crate::core::authentication_client::AuthenticationServiceClient::new(+ auth_config,+ &req_identifier,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to create auth client")?;++ let authenticate_req = api_models::authentication::AuthenticationAuthenticateRequest {+ authentication_id,+ client_secret: None,+ sdk_information: req.sdk_information.clone(),+ device_channel: req.device_channel,+ threeds_method_comp_ind: req.threeds_method_comp_ind,+ };++ let response =+ crate::core::authentication_client::AuthenticationAuthenticateFlow::call(&state,- &business_profile,- &payment_method_details.1,- browser_info,- Some(amount),- Some(currency),- authentication::MessageCategory::Payment,- req.device_channel,- authentication.clone(),- return_url,- req.sdk_information.clone(),- req.threeds_method_comp_ind,- optional_customer.and_then(|customer| customer.email.map(pii::Email::from)),- webhook_url,- &merchant_connector_account,- &authentication_connector,- Some(payment_intent.payment_id),- authentication.force_3ds_challenge,- authentication.psd2_sca_exemption_type,- Some(routing_region),+ &client,+ authenticate_req,)- .await?;- let authentication = Box::pin(external_authentication_update_trackers(- &state,- auth_response,- authentication.clone(),- None,- platform.get_processor().get_key_store(),- None,- None,- None,- None,- req.sdk_information- .and_then(|sdk_information| sdk_information.device_details),- None,- None,- ))- .await?;- authentication::AuthenticationResponse::try_from(authentication)?+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to call authentication authenticate flow")?;++ authentication::AuthenticationResponse {+ trans_status: response+ .transaction_status+ .unwrap_or(common_enums::TransactionStatus::VerificationNotPerformed),+ acs_url: response.acs_url,+ challenge_request: response.challenge_request,+ acs_reference_number: response.acs_reference_number,+ acs_trans_id: response.acs_trans_id,+ three_dsserver_trans_id: response.three_ds_server_transaction_id,+ acs_signed_content: response.acs_signed_content,+ challenge_request_key: None,+ error_message: response.error_message,+ }} else {+ let authentication = db+ .find_authentication_by_merchant_id_authentication_id(+ processor_merchant_id,+ &payment_attempt+ .authentication_id+ .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)+ .attach_printable("Error while fetching authentication record")?;Box::pin(authentication_core::perform_authentication(&state,business_profile.merchant_id,diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 3ac655b053..459500a3de 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -45,10 +45,9 @@ use crate::{metrics,payment_methods::transformers as pm_transformers,payments::{- self, helpers, operations,- operations::payment_confirm::unified_authentication_service::ThreeDsMetaData,- populate_installment_details, populate_surcharge_details, CustomerDetails,- OperationSessionGetters, OperationSessionSetters, PaymentAddress, PaymentData,+ self, helpers, operations, populate_installment_details, populate_surcharge_details,+ CustomerDetails, OperationSessionGetters, OperationSessionSetters, PaymentAddress,+ PaymentData,},three_ds_decision_rule,unified_authentication_service::{@@ -1751,11 +1750,6 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> formandate_type,).await?;- let key_manager_state = &(state).into();- let dimensions = dimension_state::Dimensions::new()- .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())- .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())- .with_organization_id(payment_data.payment_attempt.organization_id.clone());if let Some(unified_authentication_service_flow) = unified_authentication_service_flow {match unified_authentication_service_flow {@@ -1918,123 +1912,19 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> foracquirer_details,..} => {- let (authentication_connector, three_ds_connector_account) =+ let (authentication_connector, _three_ds_connector_account) =authentication::utils::get_authentication_connector_data(state, platform.get_processor(), business_profile, None).await?;- let authentication_connector_name = authentication_connector.to_string();- let authentication_id =- common_utils::id_type::AuthenticationId::generate_authentication_id(consts::AUTHENTICATION_ID_PREFIX);- let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) = if let Some(details) = &acquirer_details {- (- Some(details.acquirer_bin.clone()),- Some(details.acquirer_merchant_id.clone()),- details.acquirer_country_code.clone(),- )- } else {- (None, None, None)- };- let authentication = uas_utils::create_new_authentication(- state,- business_profile.merchant_id.clone(),- Some(authentication_connector_name.clone()),- business_profile.get_id().to_owned(),- Some(payment_data.payment_intent.payment_id.clone()),- Some(three_ds_connector_account- .get_mca_id()- .ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Error while finding mca_id from merchant_connector_account")?),- &authentication_id,- payment_data.service_details.clone(),- common_enums::AuthenticationStatus::Started,- None,- payment_data.payment_attempt.organization_id.clone(),- payment_data.payment_intent.force_3ds_challenge,- payment_data.payment_intent.psd2_sca_exemption_type,- acquirer_bin,- acquirer_merchant_id,- acquirer_country_code,- Some(payment_data.payment_intent.amount),- payment_data.payment_intent.currency,- None,- None,- None,- platform.get_processor(),- platform.get_initiator(),- )- .await?;- // Resolve acquirer details from the bucket using the card network from payment_method_data.- // The bucket is keyed by profile_acquirer_id; within it we match the card's network.- let resolved_card_network = payment_data- .payment_method_data- .as_ref()- .and_then(|pmd| match pmd {- domain::PaymentMethodData::Card(card) => card.card_network.clone(),- domain::PaymentMethodData::CardWithOptionalCVC(card) => card.card_network.clone(),- _ => None,- });- let acquirer_configs = authentication- .profile_acquirer_id- .clone()- .zip(resolved_card_network)- .and_then(|(acquirer_id, network)| {- business_profile- .acquirer_config_map.as_ref()- .and_then(|acquirer_config_map| acquirer_config_map.configs.get(&acquirer_id))- .and_then(|bucket| bucket.iter().find(|cfg| cfg.network == network).cloned())- });- let metadata: Option<ThreeDsMetaData> = three_ds_connector_account- .get_metadata()- .map(|metadata| {- metadata- .expose()- .parse_value("ThreeDsMetaData")- .attach_printable("Error while parsing ThreeDsMetaData")- })- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)?;- let merchant_country_code = authentication.acquirer_country_code.clone();++let return_url = helpers::create_authorize_url(&state.base_url,&payment_data.payment_attempt.clone(),payment_data.payment_attempt.connector.as_ref().get_required_value("connector")?,);- let three_ds_mca_id = three_ds_connector_account.get_mca_id();-- let merchant_connector_account_id_or_connector_name = three_ds_mca_id- .as_ref()- .map(|mca_id| mca_id.get_string_repr())- .unwrap_or(&authentication_connector_name);- let webhook_url = Some(url::Url::parse(&helpers::create_webhook_url(- &state.base_url,- &authentication.merchant_id,- merchant_connector_account_id_or_connector_name,- )))- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse webhook notification url")?;-- let notification_url = Some(url::Url::parse(&return_url))- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse authorise notification 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().and_then(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)),- 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.clone().map(common_types::payments::MerchantCountryCode::new),- notification_url,- webhook_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+ let domain_address = payment_data.address.get_payment_method_billing().map(|address| address.clone().foreign_into());+ let shipping = payment_data.address.get_shipping().map(|address| address.clone().foreign_into());+ let browser_info: Option<api_models::payments::BrowserInformation> = payment_data.payment_attempt.browser_info.clone().parse_value("BrowserInfo").change_context(errors::ApiErrorResponse::InternalServerError)@@ -2052,53 +1942,114 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.change_context(errors::StorageError::DeserializationFailed).attach_printable("Failed to parse customer data from payment intent").change_context(errors::ApiErrorResponse::InternalServerError)?.and_then(|cust| cust.email);- let routing_region =- uas_utils::utils::fetch_routing_region_for_uas(state, &dimensions).await;- let pre_auth_response = uas_utils::types::ExternalAuthentication::pre_authentication(- state,- &payment_data.payment_attempt.merchant_id,- Some(&payment_data.payment_intent.payment_id),- payment_data.payment_method_data.as_ref(),- payment_data.payment_attempt.payment_method_type,- &three_ds_connector_account,- &authentication_connector_name,- &authentication.authentication_id,- payment_data.payment_attempt.payment_method.ok_or(- errors::ApiErrorResponse::InternalServerError- ).attach_printable("payment_method not found in payment_attempt")?,- payment_data.payment_intent.amount,- payment_data.payment_intent.currency,- payment_data.service_details.clone(),- merchant_details.as_ref(),- domain_address,- authentication.acquirer_bin.clone(),- authentication.acquirer_merchant_id.clone(),- Some(routing_region),- )- .await?;- let updated_authentication = Box::pin(uas_utils::utils::external_authentication_update_trackers(+ let authentication_acquirer_details = api_models::authentication::AcquirerDetails {+ merchant_country_code: acquirer_details.as_ref().and_then(|details| details.acquirer_country_code.clone()),+ acquirer_bin: acquirer_details.as_ref().map(|details| details.acquirer_bin.clone()),+ acquirer_merchant_id: acquirer_details.as_ref().map(|details| details.acquirer_merchant_id.clone())+ };++ let (authentication_create_response, eligibility_response) = {+ let auth_config = &state.conf.micro_services.authentication_service;+ let currency = payment_data.payment_intent.currency.ok_or(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "currency",+ }).attach_printable("Currency missing")?;++ let req_identifier = router_env::RequestIdentifier::new("x-request-id");+ let client = crate::core::authentication_client::AuthenticationServiceClient::new(+ auth_config,+ &req_identifier,+ ).change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to create auth client")?;++ let auth_req = api_models::authentication::AuthenticationCreateRequest {+ authentication_id: None,+ profile_id: None,+ amount: payment_data.payment_intent.amount,+ authentication_connector: Some(authentication_connector),+ currency,+ return_url: Some(return_url),+ force_3ds_challenge: payment_data.payment_intent.force_3ds_challenge,+ psd2_sca_exemption_type: payment_data.payment_intent.psd2_sca_exemption_type,+ profile_acquirer_id: None,+ acquirer_details: Some(authentication_acquirer_details),+ customer_details: None,+ };++ let auth_create_resp = crate::core::authentication_client::AuthenticationCreateFlow::call(state,- pre_auth_response,- authentication.clone(),- acquirer_details,- platform.get_processor().get_key_store(),- domain_address.cloned(),- shipping.cloned(),- email,- browser_info,- None,- 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 present- authentication: updated_authentication.clone(),+ &client,+ auth_req,+ ).await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to call authentication create flow")?;+ payment_data.payment_attempt.authentication_id = Some(auth_create_resp.authentication_id.clone());++ let pm_data: api_models::payments::PaymentMethodData = match payment_data.payment_method_data.clone() {+ Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card)) => {+ api_models::payments::PaymentMethodData::Card(+ api_models::payments::Card {+ card_number: card.card_number,+ card_exp_month: card.card_exp_month,+ card_exp_year: card.card_exp_year,+ card_holder_name: card.card_holder_name,+ card_cvc: card.card_cvc,+ card_issuer: card.card_issuer,+ card_network: card.card_network,+ card_type: card.card_type,+ card_issuing_country: card.card_issuing_country,+ card_issuing_country_code: card.card_issuing_country_code,+ bank_code: card.bank_code,+ nick_name: card.nick_name,+ }+ )+ },+ Some(_) => {+ Err(errors::ApiErrorResponse::NotSupported {+ message: "Payment method not supported for modular authentication".to_string(),+ })+ .attach_printable("Unsupported payment method for modular authentication")?+ }+ None => {+ Err(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "payment_method_data",+ })+ .attach_printable("payment_method_data missing in payment_data")?+ }};- payment_data.authentication = Some(authentication_store.clone());- if updated_authentication.is_separate_authn_required()- || updated_authentication.authentication_status.is_failed()+ let eligibility_req = api_models::authentication::AuthenticationEligibilityRequest {+ payment_method_data: pm_data,+ payment_method: payment_data+ .payment_attempt+ .payment_method+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("payment_method not found in payment_attempt")?,+ payment_method_type: payment_data.payment_attempt.payment_method_type,+ client_secret: None,+ profile_id: payment_data.payment_intent.profile_id.clone(),+ billing: domain_address,+ shipping,+ browser_information: browser_info.clone(),+ email: email.clone(),+ };++ let elig_resp = crate::core::authentication_client::AuthenticationEligibilityFlow::call(+ state,+ &client,+ (+ eligibility_req,+ auth_create_resp.authentication_id.get_string_repr().to_owned(),+ ),+ ).await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to call authentication eligibility flow")?;++ (auth_create_resp, elig_resp)+ };++ if eligibility_response.is_separate_authn_required()+ || eligibility_response.status.is_failed(){*should_continue_confirm_transaction = false;let default_poll_config = types::PollConfig::default();@@ -2108,15 +2059,15 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.attach_printable("Error while stringifying default poll config")?;// raise error if authentication_connector is not present since it should we be present in the current flow- let authentication_connector = updated_authentication.authentication_connector+ let authentication_connector = eligibility_response.authentication_connector.ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("authentication_connector not found in updated_authentication")?;+ .attach_printable("authentication_connector not found in eligibility_response")?;let poll_config = state.store.find_config_by_key_unwrap_or(&types::PollConfig::get_poll_config_key(- authentication_connector.clone(),+ authentication_connector.to_string()),Some(default_config_str),)@@ -2130,9 +2081,33 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.attach_printable("Error while parsing PollConfig")?;payment_data.poll_config = Some(poll_config)}++ let three_ds_data = eligibility_response.eligibility_response_params.as_ref().map(|param| {+ match param {+ api_models::authentication::EligibilityResponseParams::ThreeDsData(data) => data.clone(),+ }+ });++ let authentication_domain_model = authentication::transformers::construct_authentication_domain_model(+ (+ authentication_create_response.clone(),+ eligibility_response.clone(),+ three_ds_data.clone(),+ payment_data.payment_attempt.profile_id.clone(),+ payment_data.payment_attempt.organization_id.clone(),+ )+ );++ let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {+ cavv: None,+ authentication:authentication_domain_model+ };++ payment_data.authentication = Some(authentication_store.clone());+},helpers::UnifiedAuthenticationServiceFlow::ExternalAuthenticationPostAuthenticate {authentication_id} => {- let (authentication_connector, three_ds_connector_account) =+ let (_authentication_connector, three_ds_connector_account) =authentication::utils::get_authentication_connector_data(state, platform.get_processor(), business_profile, None).await?;let is_pull_mechanism_enabled =utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(@@ -2140,69 +2115,61 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.get_metadata().map(|metadata| metadata.expose()),);- let authentication = state- .store- .find_authentication_by_merchant_id_authentication_id(- &business_profile.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()))?;- let routing_region =- uas_utils::utils::fetch_routing_region_for_uas(state, &dimensions).await;+ let sync_response = if !payment_data.payment_attempt.status.is_terminal_status() && is_pull_mechanism_enabled {+ {+ let auth_config = &state.conf.micro_services.authentication_service;+ let req_identifier = router_env::RequestIdentifier::new("x-request-id");+ let client = crate::core::authentication_client::AuthenticationServiceClient::new(+ auth_config,+ &req_identifier,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to create auth client")?;++ let sync_req = api_models::authentication::AuthenticationSyncRequest {+ client_secret: None,+ payment_method_details: None,+ authentication_id: authentication_id.clone(),+ };- let updated_authentication = if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled {- let post_auth_response = uas_utils::types::ExternalAuthentication::post_authentication(- state,- business_profile,- Some(&payment_data.payment_intent.payment_id),- &three_ds_connector_account,- &authentication_connector.to_string(),- &authentication.authentication_id,- payment_data.payment_attempt.payment_method.ok_or(- errors::ApiErrorResponse::InternalServerError- ).attach_printable("payment_method not found in payment_attempt")?,- &payment_data.payment_intent.merchant_id,- Some(&authentication),- Some(routing_region)- ).await?;- uas_utils::utils::external_authentication_update_trackers(- state,- post_auth_response,- authentication,- None,- platform.get_processor().get_key_store(),- None,- None,- None,- None,- None,- None,- None,- ).await?+ let response = crate::core::authentication_client::AuthenticationSyncFlow::call(+ state,+ &client,+ (sync_req, business_profile.merchant_id.get_string_repr().to_owned()),+ ).await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to call authentication sync flow")?;++ response+ }} else {- authentication+ return Err(errors::ApiErrorResponse::InternalServerError).attach_printable("Pull mechanism disabled or terminal status during post-authentication sync")?;};- let tokenized_data = if updated_authentication.authentication_status.is_success() {+ let updated_authentication_status = sync_response.status;++ let authentication_domain_model = authentication::transformers::construct_authentication_domain_model(+ (+ sync_response.clone(),+ payment_data.payment_attempt.organization_id.clone(),+ )+ );++ let tokenized_data = if updated_authentication_status.is_success() {Some(crate::core::payment_methods::vault::get_tokenized_data(state, authentication_id.get_string_repr(), false, platform.get_provider().get_key_store().key.get_inner()).await?)} else {None};- let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {- cavv: tokenized_data.map(|tokenized_data| hyperswitch_masking::Secret::new(tokenized_data.value1)),- authentication: updated_authentication- };+ let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {+ cavv: tokenized_data.map(|tokenized_data| hyperswitch_masking::Secret::new(tokenized_data.value1)),+ authentication:authentication_domain_model+ };- payment_data.authentication = Some(authentication_store.clone());+ payment_data.authentication = Some(authentication_store.clone());//If authentication is not successful, skip the payment connector flows and mark the payment as failure- if authentication_store.authentication.authentication_status- != api_models::enums::AuthenticationStatus::Success+ if updated_authentication_status != api_models::enums::AuthenticationStatus::Success{*should_continue_confirm_transaction = false;}diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rsindex c62227fa99..72c3ea4882 100644--- a/crates/router/src/core/unified_authentication_service.rs+++ b/crates/router/src/core/unified_authentication_service.rs@@ -1096,25 +1096,21 @@ pub async fn authentication_eligibility_core().await?;- let notification_url = match authentication_connector {- common_enums::AuthenticationConnectors::Juspaythreedsserver => {- Some(url::Url::parse(&format!(- "{base_url}/authentication/{merchant_id}/{authentication_id}/redirect",- base_url = state.base_url,- merchant_id = merchant_id.get_string_repr(),- authentication_id = authentication_id.get_string_repr()- )))- .transpose()- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse notification url")?- }- _ => authentication- .return_url- .as_ref()- .map(|url| url::Url::parse(url))- .transpose()- .change_context(ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse return url")?,+ let notification_url = match authentication.return_url {+ Some(ref url) => Some(+ url::Url::parse(url)+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse return url")?,+ ),+ None => Some(url::Url::parse(&format!(+ "{base_url}/authentication/{merchant_id}/{authentication_id}/redirect",+ base_url = state.base_url,+ merchant_id = merchant_id.get_string_repr(),+ authentication_id = authentication_id.get_string_repr()+ )))+ .transpose()+ .change_context(ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse notification url")?,};let authentication_connector_name = authentication_connector.to_string();@@ -2195,6 +2191,7 @@ pub async fn authentication_sync_core(let dimensions = dimensions.without_organization_id();// Determine whether to tokenise or not+let should_disable_vault_tokenization = dimensions.get_should_disable_vault_tokenization(state.store.as_ref(),diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rsindex ddd7616fee..e91379aec1 100644--- a/crates/router/src/types/transformers.rs+++ b/crates/router/src/types/transformers.rs@@ -639,6 +639,12 @@ impl ForeignFrom<domain::Address> for api_types::Address {}}+impl ForeignFrom<hyperswitch_domain_models::address::Address> for payments::Address {+ fn foreign_from(address: hyperswitch_domain_models::address::Address) -> Self {+ address.into()+ }+}+implForeignFrom<(diesel_models::api_keys::ApiKey,