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
fix(authentication): fixed authentication analytics (#13442)
Sahkal Poddara0e755abfc11
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rsindex 011633dce3..7d86b0c948 100644--- a/crates/analytics/src/auth_events/core.rs+++ b/crates/analytics/src/auth_events/core.rs@@ -24,6 +24,15 @@ use crate::{AnalyticsProvider,};+fn numeric_country_code_to_alpha2(country_code: String) -> String {+ country_code+ .parse::<u32>()+ .ok()+ .and_then(|code| common_enums::Country::from_numeric(code).ok())+ .map(|country| country.to_alpha2().to_string())+ .unwrap_or(country_code)+}+#[instrument(skip_all)]pub async fn get_metrics(pool: &AnalyticsProvider,@@ -182,20 +191,17 @@ pub async fn get_filters(AuthEventDimensions::Platform => fil.platform,AuthEventDimensions::Mcc => fil.mcc,AuthEventDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()),- AuthEventDimensions::MerchantCountry => fil.merchant_country,+ AuthEventDimensions::MerchantCountry => fil.merchant_country.map(numeric_country_code_to_alpha2),AuthEventDimensions::BillingCountry => fil.billing_country,- AuthEventDimensions::ShippingCountry => fil.shipping_country,- AuthEventDimensions::IssuerCountry => fil.issuer_country,+ AuthEventDimensions::ShippingCountry => fil.shipping_country,+ AuthEventDimensions::IssuerCountry => fil+ .issuer_country+ .map(numeric_country_code_to_alpha2),AuthEventDimensions::EarliestSupportedVersion => fil.earliest_supported_version,AuthEventDimensions::LatestSupportedVersion => fil.latest_supported_version,- AuthEventDimensions::WhitelistDecision => fil.whitelist_decision.map(|i| i.to_string()),- AuthEventDimensions::DeviceManufacturer => fil.device_manufacturer,AuthEventDimensions::DeviceType => fil.device_type,- AuthEventDimensions::DeviceBrand => fil.device_brand,AuthEventDimensions::DeviceOs => fil.device_os,AuthEventDimensions::DeviceDisplay => fil.device_display,- AuthEventDimensions::BrowserName => fil.browser_name,- AuthEventDimensions::BrowserVersion => fil.browser_version,AuthEventDimensions::IssuerId => fil.issuer_id,AuthEventDimensions::SchemeName => fil.scheme_name,AuthEventDimensions::ExemptionRequested => fil.exemption_requested.map(|i| i.to_string()),diff --git a/crates/analytics/src/auth_events/sankey.rs b/crates/analytics/src/auth_events/sankey.rsindex ede90ad9a8..711b595dc2 100644--- a/crates/analytics/src/auth_events/sankey.rs+++ b/crates/analytics/src/auth_events/sankey.rs@@ -1,4 +1,4 @@-use common_enums::AuthenticationStatus;+use common_enums::{AuthenticationStatus, DecoupledAuthenticationType};use common_utils::{errors::ParsingError,types::{authentication::AuthInfo, TimeRange},@@ -16,6 +16,7 @@ use crate::{pub struct SankeyRow {pub count: i64,pub authentication_status: Option<AuthenticationStatus>,+ pub authentication_type: Option<DecoupledAuthenticationType>,pub exemption_requested: Option<bool>,pub exemption_accepted: Option<bool>,}@@ -58,6 +59,10 @@ pub async fn get_sankey_data(.add_select_column("authentication_status").change_context(MetricsError::QueryBuildingError)?;+ query_builder+ .add_select_column("authentication_type")+ .change_context(MetricsError::QueryBuildingError)?;+auth.set_filter_clause(&mut query_builder).change_context(MetricsError::QueryBuildingError)?;@@ -77,6 +82,10 @@ pub async fn get_sankey_data(.add_group_by_clause("authentication_status").change_context(MetricsError::QueryBuildingError)?;+ query_builder+ .add_group_by_clause("authentication_type")+ .change_context(MetricsError::QueryBuildingError)?;+query_builder.execute_query::<SankeyRow, _>(clickhouse_client).awaitdiff --git a/crates/analytics/src/auth_events/types.rs b/crates/analytics/src/auth_events/types.rsindex 4aaa262267..bde06beeb3 100644--- a/crates/analytics/src/auth_events/types.rs+++ b/crates/analytics/src/auth_events/types.rs@@ -6,6 +6,19 @@ use crate::{types::{AnalyticsCollection, AnalyticsDataSource},};+fn country_code_to_numeric(country_code: &str) -> String {+ country_code+ .to_ascii_uppercase()+ .parse::<common_enums::CountryAlpha2>()+ .map(|alpha2| {+ format!(+ "{:03}",+ common_enums::Country::from_alpha2(alpha2).to_numeric()+ )+ })+ .unwrap_or_else(|_| country_code.to_string())+}+impl<T> QueryFilter<T> for AuthEventFilterswhereT: AnalyticsDataSource,@@ -80,10 +93,15 @@ where.attach_printable("Failed to add currency filter")?;}if !self.merchant_country.is_empty() {+ let merchant_countries = self+ .merchant_country+ .iter()+ .map(|country| country_code_to_numeric(country))+ .collect::<Vec<_>>();builder.add_filter_in_range_clause(AuthEventDimensions::MerchantCountry,- &self.merchant_country,+ &merchant_countries,).attach_printable("Failed to add merchant country filter")?;}@@ -104,11 +122,13 @@ where.attach_printable("Failed to add shipping country filter")?;}if !self.issuer_country.is_empty() {+ let issuer_countries = self+ .issuer_country+ .iter()+ .map(|country| country_code_to_numeric(country))+ .collect::<Vec<_>>();builder- .add_filter_in_range_clause(- AuthEventDimensions::IssuerCountry,- &self.issuer_country,- )+ .add_filter_in_range_clause(AuthEventDimensions::IssuerCountry, &issuer_countries).attach_printable("Failed to add issuer country filter")?;}if !self.earliest_supported_version.is_empty() {@@ -127,32 +147,11 @@ where).attach_printable("Failed to add latest supported version filter")?;}- if !self.whitelist_decision.is_empty() {- builder- .add_filter_in_range_clause(- AuthEventDimensions::WhitelistDecision,- &self.whitelist_decision,- )- .attach_printable("Failed to add whitelist decision filter")?;- }- if !self.device_manufacturer.is_empty() {- builder- .add_filter_in_range_clause(- AuthEventDimensions::DeviceManufacturer,- &self.device_manufacturer,- )- .attach_printable("Failed to add device manufacturer filter")?;- }if !self.device_type.is_empty() {builder.add_filter_in_range_clause(AuthEventDimensions::DeviceType, &self.device_type).attach_printable("Failed to add device type filter")?;}- if !self.device_brand.is_empty() {- builder- .add_filter_in_range_clause(AuthEventDimensions::DeviceBrand, &self.device_brand)- .attach_printable("Failed to add device brand filter")?;- }if !self.device_os.is_empty() {builder.add_filter_in_range_clause(AuthEventDimensions::DeviceOs, &self.device_os)@@ -166,19 +165,6 @@ where).attach_printable("Failed to add device display filter")?;}- if !self.browser_name.is_empty() {- builder- .add_filter_in_range_clause(AuthEventDimensions::BrowserName, &self.browser_name)- .attach_printable("Failed to add browser name filter")?;- }- if !self.browser_version.is_empty() {- builder- .add_filter_in_range_clause(- AuthEventDimensions::BrowserVersion,- &self.browser_version,- )- .attach_printable("Failed to add browser version filter")?;- }if !self.issuer_id.is_empty() {builder.add_filter_in_range_clause(AuthEventDimensions::IssuerId, &self.issuer_id)diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rsindex 36121e56eb..52bb134897 100644--- a/crates/analytics/src/utils.rs+++ b/crates/analytics/src/utils.rs@@ -63,14 +63,9 @@ pub fn get_auth_event_dimensions() -> Vec<NameDescription> {AuthEventDimensions::IssuerId,AuthEventDimensions::EarliestSupportedVersion,AuthEventDimensions::LatestSupportedVersion,- AuthEventDimensions::WhitelistDecision,- AuthEventDimensions::DeviceManufacturer,AuthEventDimensions::DeviceType,- AuthEventDimensions::DeviceBrand,AuthEventDimensions::DeviceOs,AuthEventDimensions::DeviceDisplay,- AuthEventDimensions::BrowserName,- AuthEventDimensions::BrowserVersion,AuthEventDimensions::SchemeName,AuthEventDimensions::ExemptionRequested,AuthEventDimensions::ExemptionAccepted,diff --git a/crates/api_models/src/analytics/auth_events.rs b/crates/api_models/src/analytics/auth_events.rsindex f1062e0269..a3fcfec0d4 100644--- a/crates/api_models/src/analytics/auth_events.rs+++ b/crates/api_models/src/analytics/auth_events.rs@@ -105,14 +105,9 @@ pub enum AuthEventDimensions {IssuerCountry,EarliestSupportedVersion,LatestSupportedVersion,- WhitelistDecision,- DeviceManufacturer,DeviceType,- DeviceBrand,DeviceOs,DeviceDisplay,- BrowserName,- BrowserVersion,IssuerId,SchemeName,ExemptionRequested,diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rsindex fe10723ddf..5e03c33b7e 100644--- a/crates/diesel_models/src/authentication.rs+++ b/crates/diesel_models/src/authentication.rs@@ -266,6 +266,8 @@ pub enum AuthenticationUpdate {device_brand: Option<String>,device_os: Option<String>,device_display: Option<String>,+ platform: Option<String>,+ exemption_accepted: Option<bool>,updated_by: String,},PostAuthenticationUpdate {@@ -547,6 +549,8 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {device_brand,device_os,device_display,+ platform,+ exemption_accepted,updated_by,} => Self {trans_status: Some(trans_status),@@ -569,6 +573,8 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {device_brand,device_os,device_display,+ platform,+ exemption_accepted,updated_by,..Default::default()},diff --git a/crates/hyperswitch_domain_models/src/authentication.rs b/crates/hyperswitch_domain_models/src/authentication.rsindex 8473fd5f60..9b375216d9 100644--- a/crates/hyperswitch_domain_models/src/authentication.rs+++ b/crates/hyperswitch_domain_models/src/authentication.rs@@ -540,6 +540,8 @@ pub enum AuthenticationUpdate {device_brand: Option<String>,device_os: Option<String>,device_display: Option<String>,+ platform: Option<api_models::payments::DeviceChannel>,+ exemption_accepted: Option<bool>,updated_by: String,},PostAuthenticationUpdate {@@ -677,6 +679,8 @@ impl From<AuthenticationUpdate> for diesel_models::authentication::Authenticatiodevice_brand,device_os,device_display,+ platform,+ exemption_accepted,updated_by,} => Self::AuthenticationUpdate {trans_status,@@ -699,6 +703,8 @@ impl From<AuthenticationUpdate> for diesel_models::authentication::Authenticatiodevice_brand,device_os,device_display,+ platform: platform.map(|platform| platform.to_string()),+ exemption_accepted,updated_by,},AuthenticationUpdate::PostAuthenticationUpdate {diff --git a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rsindex d62407f8c2..8a50f2c090 100644--- a/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types/authentication.rs@@ -194,6 +194,7 @@ pub struct AuthenticationInfo {pub device_details: Option<api_models::payments::DeviceDetails>,pub merchant_category_code: Option<common_enums::MerchantCategoryCode>,pub merchant_country_code: Option<common_enums::CountryAlpha2>,+ pub platform: Option<api_models::payments::DeviceChannel>,}#[cfg(feature = "v1")]@@ -207,6 +208,7 @@ impl From<api_models::authentication::AuthenticationEligibilityRequest> for Authdevice_details: None,merchant_category_code: None,merchant_country_code: None,+ platform: None,}}}diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rsindex f6ab00a5f0..ccbde05654 100644--- a/crates/router/src/core/authentication.rs+++ b/crates/router/src/core/authentication.rs@@ -61,7 +61,7 @@ pub async fn perform_authentication(amount,currency,message_category,- device_channel,+ device_channel.clone(),merchant_connector_account,authentication_data.clone(),return_url,@@ -91,6 +91,7 @@ pub async fn perform_authentication(.and_then(|sdk_information| sdk_information.device_details),merchant_category_code: None,merchant_country_code: None,+ platform: Some(device_channel),};let authentication = Box::pin(utils::update_trackers(state,@@ -179,6 +180,7 @@ pub async fn perform_post_authentication(device_details: None,merchant_category_code: None,merchant_country_code: None,+ platform: None,};utils::update_trackers(@@ -232,7 +234,10 @@ pub async fn perform_pre_authentication(psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,billing_address: Option<hyperswitch_domain_models::address::Address>,shipping_address: Option<hyperswitch_domain_models::address::Address>,+ browser_info: Option<core_types::BrowserInformation>,initiator: Option<&domain::Initiator>,+ amount: Option<common_utils::types::MinorUnit>,+ currency: Option<Currency>,) -> CustomResult<hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,ApiErrorResponse,@@ -245,7 +250,7 @@ pub async fn perform_pre_authentication(provider_merchant_id,authentication_connector_name.clone(),token,- business_profile.get_id().to_owned(),+ business_profile,payment_id.clone(),three_ds_connector_account.get_mca_id()@@ -256,6 +261,13 @@ pub async fn perform_pre_authentication(psd2_sca_exemption_type,processor,initiator,+ &card,+ browser_info.as_ref(),+ acquirer_details.as_ref(),+ billing_address.as_ref(),+ shipping_address.as_ref(),+ amount,+ currency,).await?;@@ -285,6 +297,7 @@ pub async fn perform_pre_authentication(device_details: None,merchant_category_code: None,merchant_country_code: None,+ platform: None,};let updated_authentication = Box::pin(utils::update_trackers(@@ -335,6 +348,7 @@ pub async fn perform_pre_authentication(device_details: None,merchant_category_code: None,merchant_country_code: None,+ platform: None,};let authentication_update = Box::pin(utils::update_trackers(diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rsindex 28cfd8017c..b222995984 100644--- a/crates/router/src/core/authentication/utils.rs+++ b/crates/router/src/core/authentication/utils.rs@@ -238,6 +238,10 @@ pub async fn update_trackers<F: Clone, Req>(let authentication_status =common_enums::AuthenticationStatus::foreign_from(trans_status.clone());+ let exemption_accepted = authentication+ .psd2_sca_exemption_type+ .as_ref()+ .map(|_| matches!(&trans_status, common_enums::TransactionStatus::Success));authentication::AuthenticationUpdate::AuthenticationUpdate {trans_status,@@ -272,6 +276,8 @@ pub async fn update_trackers<F: Clone, Req>(.device_details.as_ref().and_then(|device_details| device_details.device_display.clone()),+ platform: authentication_info.platform,+ exemption_accepted,updated_by: storage_scheme.to_string(),}}@@ -375,7 +381,7 @@ pub async fn create_new_authentication(merchant_id: common_utils::id_type::MerchantId,authentication_connector: String,token: String,- profile_id: common_utils::id_type::ProfileId,+ business_profile: &domain::Profile,payment_id: common_utils::id_type::PaymentId,merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,organization_id: common_utils::id_type::OrganizationId,@@ -383,6 +389,13 @@ pub async fn create_new_authentication(psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,processor: &domain::Processor,initiator: Option<&domain::Initiator>,+ card: &hyperswitch_domain_models::payment_method_data::Card,+ browser_info: Option<&router_request_types::BrowserInformation>,+ acquirer_details: Option<&super::types::AcquirerDetails>,+ billing_address: Option<&hyperswitch_domain_models::address::Address>,+ shipping_address: Option<&hyperswitch_domain_models::address::Address>,+ amount: Option<common_utils::types::MinorUnit>,+ currency: Option<common_enums::Currency>,) -> RouterResult<authentication::Authentication> {let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id(consts::AUTHENTICATION_ID_PREFIX,@@ -396,6 +409,41 @@ pub async fn create_new_authentication(let current_time = common_utils::date_time::now();+ let issuer_country = card+ .card_issuing_country_code+ .clone()+ .or(card.card_issuing_country.clone());+ let device_type = browser_info.and_then(|info| info.device_model.clone());+ let device_os = browser_info.and_then(|info| match (&info.os_type, &info.os_version) {+ (Some(os_type), Some(os_version)) => Some(format!("{os_type}-{os_version}")),+ (Some(os_type), None) => Some(os_type.clone()),+ (None, Some(os_version)) => Some(os_version.clone()),+ (None, None) => None,+ });+ let device_display =+ browser_info.and_then(|info| match (info.screen_width, info.screen_height) {+ (Some(width), Some(height)) => Some(format!("{width}x{height}")),+ _ => None,+ });+ let browser_info = browser_info+ .map(common_utils::ext_traits::Encode::encode_to_value)+ .transpose()+ .change_context(errors::ApiErrorResponse::InvalidDataValue {+ field_name: "browser_information",+ })?;+ let billing_country = billing_address.and_then(|billing| {+ billing+ .address+ .as_ref()+ .and_then(|address| address.country.map(|country| country.to_string()))+ });+ let shipping_country = shipping_address.and_then(|shipping| {+ shipping+ .address+ .as_ref()+ .and_then(|address| address.country.map(|country| country.to_string()))+ });+let new_authentication = authentication::Authentication {authentication_id: authentication_id.clone(),merchant_id,@@ -418,8 +466,8 @@ pub async fn create_new_authentication(message_version: None,eci: None,trans_status: None,- acquirer_bin: None,- acquirer_merchant_id: None,+ acquirer_bin: acquirer_details.map(|details| details.acquirer_bin.clone()),+ acquirer_merchant_id: acquirer_details.map(|details| details.acquirer_merchant_id.clone()),three_ds_method_data: None,three_ds_method_url: None,acs_url: None,@@ -427,31 +475,35 @@ pub async fn create_new_authentication(acs_reference_number: None,acs_trans_id: None,acs_signed_content: None,- profile_id,+ profile_id: business_profile.get_id().to_owned(),payment_id: Some(payment_id),merchant_connector_id: Some(merchant_connector_id),ds_trans_id: None,directory_server_id: None,- acquirer_country_code: None,+ acquirer_country_code: acquirer_details+ .and_then(|details| details.acquirer_country_code.clone()),organization_id,- mcc: None,- amount: None,- currency: None,- billing_country: None,- shipping_country: None,- issuer_country: None,+ mcc: business_profile.merchant_category_code.clone(),+ amount,+ currency,+ billing_country,+ shipping_country,+ issuer_country,earliest_supported_version: None,latest_supported_version: None,platform: None,- device_type: None,+ device_type,device_brand: None,- device_os: None,- device_display: None,+ device_os,+ device_display,browser_name: None,browser_version: None,- issuer_id: None,- scheme_name: None,- exemption_requested: None,+ issuer_id: card+ .card_issuer+ .as_ref()+ .map(|issuer_id| issuer_id.replace(' ', "")),+ scheme_name: card.card_network.as_ref().map(ToString::to_string),+ exemption_requested: psd2_sca_exemption_type.map(|_| true),exemption_accepted: None,service_details: None,authentication_client_secret,@@ -460,7 +512,7 @@ pub async fn create_new_authentication(return_url: None,billing_address: None,shipping_address: None,- browser_info: None,+ browser_info,email: None,profile_acquirer_id: None,challenge_code: None,@@ -469,7 +521,10 @@ pub async fn create_new_authentication(message_extension: None,challenge_request_key: None,customer_details: None,- merchant_country_code: None,+ merchant_country_code: business_profile+ .merchant_country_code+ .as_ref()+ .map(|country_code| country_code.get_country_code()),processor_merchant_id: Some(processor.get_account().get_id().clone()),created_by: initiator.and_then(|initiator| initiator.to_created_by()),// Seed with the configured scheme; the insert layer overwrites with the decided one.diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 841dee5f36..c50fd8487b 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -1517,6 +1517,15 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for}) => {let billing_address = payment_data.address.get_payment_method_billing().cloned();let shipping = payment_data.address.get_shipping().cloned();+ let browser_info: Option<+ hyperswitch_domain_models::router_request_types::BrowserInformation,+ > = payment_data+ .payment_attempt+ .browser_info+ .clone()+ .parse_value("BrowserInfo")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse browser_info")?;let authentication_store = Box::pin(authentication::perform_pre_authentication(state,processor,@@ -1531,7 +1540,10 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forpayment_data.payment_intent.psd2_sca_exemption_type,billing_address,shipping,+ browser_info,initiator,+ Some(payment_data.payment_intent.amount),+ payment_data.payment_intent.currency,)).await?;if authentication_storediff --git a/crates/router/src/core/unified_authentication_service/utils.rs b/crates/router/src/core/unified_authentication_service/utils.rsindex 7aadbc5fcd..8e1a5780cd 100644--- a/crates/router/src/core/unified_authentication_service/utils.rs+++ b/crates/router/src/core/unified_authentication_service/utils.rs@@ -319,6 +319,13 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(let authentication_status = common_enums::AuthenticationStatus::foreign_from(authentication_details.trans_status.clone(),);+ let exemption_accepted =+ authentication.psd2_sca_exemption_type.as_ref().map(|_| {+ matches!(+ &authentication_details.trans_status,+ common_enums::TransactionStatus::Success+ )+ });authentication_details.authentication_value.async_map(|auth_val| {@@ -375,6 +382,8 @@ pub async fn external_authentication_update_trackers<F: Clone, Req>(device_display: device_details.as_ref().and_then(|details| details.device_display.clone()),+ platform: None,+ exemption_accepted,updated_by: storage_scheme.to_string(),},)