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(FRM): FRM flow fixes [AccessToken Check] [Merchant Connector Ref Id fix] (#14494)
Ritam Kabiraj5428b5f89872
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rsindex 5662f9a0ac..2cd3c8fe47 100644--- a/crates/common_enums/src/connector_enums.rs+++ b/crates/common_enums/src/connector_enums.rs@@ -311,6 +311,12 @@ impl Connector {pub fn supports_vendor_disburse_account_create_for_payout(self) -> bool {matches!(self, Self::Stripe | Self::Nomupay)}+ /// Whether this FRM provider's risk API is bearer-authenticated, so a token+ /// must be fetched before the risk check. Static-key providers (nSure) and+ /// the in-process ones need none; add a provider here when it requires one.+ pub fn supports_access_token_for_frm(self) -> bool {+ false+ }pub fn supports_access_token(self, payment_method: PaymentMethod) -> bool {matches!((self, payment_method),diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rsindex a4328d536e..7c34e9a02f 100644--- a/crates/router/src/core/fraud_check.rs+++ b/crates/router/src/core/fraud_check.rs@@ -51,6 +51,7 @@ use crate::{},utils::ValueExt,};+pub mod access_token;pub mod flows;#[cfg(feature = "v1")]pub mod gateway;diff --git a/crates/router/src/core/fraud_check/access_token.rs b/crates/router/src/core/fraud_check/access_token.rsnew file mode 100644index 0000000000..ace18f8ff1--- /dev/null+++ b/crates/router/src/core/fraud_check/access_token.rs@@ -0,0 +1,30 @@+//! Access-token handling for FRM providers, the FRM counterpart of+//! `payments::access_token` and `payouts::access_token`.++use std::str::FromStr;++use common_enums::connector_enums::Connector;+use hyperswitch_domain_models::router_data::RouterData;++use crate::services::logger;++/// Attach the access token a bearer-authenticated FRM provider needs before the+/// risk check. Providers outside `Connector::supports_access_token_for_frm`+/// (static-key ones such as nSure) are left untouched, so no token call is made+/// for them.+pub fn add_access_token_for_frm<F, Req, Res>(router_data: &mut RouterData<F, Req, Res>) {+ let connector_supports_access_token = Connector::from_str(&router_data.connector)+ .is_ok_and(|connector| connector.supports_access_token_for_frm());++ if !connector_supports_access_token || router_data.access_token.is_some() {+ return;+ }++ // Fetching the token (Redis cache first, then UCS `create_access_token`, as+ // payments does) will be implemented based on requirement, once a+ // bearer-authenticated FRM provider is onboarded.+ logger::warn!(+ connector = %router_data.connector,+ "Access token fetch is not implemented for FRM providers; continuing without one"+ );+}diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rsindex 8f877b4f49..740630ddab 100644--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs@@ -164,7 +164,10 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudCpayment_method_token: self.payment_method_token.clone(),connector_customer: None,preprocessing_id: None,- connector_request_reference_id: common_utils::generate_uuid_v4().to_string(),+ // The `fraud_check` row id identifies this risk evaluation; providers+ // key it as the transaction reference, and follow-up calls resolve the+ // same row through the attempt's `active_frm_id`.+ connector_request_reference_id: self.fraud_check.frm_id.clone(),test_mode: None,recurring_mandate_payment_data: None,#[cfg(feature = "payouts")]diff --git a/crates/router/src/core/fraud_check/gateway.rs b/crates/router/src/core/fraud_check/gateway.rsindex b06c1606b8..ab4b0638d4 100644--- a/crates/router/src/core/fraud_check/gateway.rs+++ b/crates/router/src/core/fraud_check/gateway.rs@@ -26,11 +26,10 @@ use unified_connector_service_client::payments as payments_grpc;use crate::{core::{- payments::gateway::context::RouterGatewayContext,- unified_connector_service::{self, frm as ucs_frm},+ fraud_check::access_token, payments::gateway::context::RouterGatewayContext,+ unified_connector_service,},routes::SessionState,- services::logger,types::transformers::ForeignTryFrom,};@@ -80,22 +79,8 @@ where.ok_or(ConnectorError::RequestEncodingFailed).attach_printable("Failed to fetch Unified Connector Service client")?;- // Bearer-authenticated providers (Kount) need an OAuth token in- // `state.access_token`; static-key providers (nSure) get `None` and- // ignore it. Failure here is non-fatal — the connector surfaces a- // clear auth error rather than us guessing.let mut router_data = router_data.clone();- if router_data.access_token.is_none() {- router_data.access_token = ucs_frm::get_frm_access_token(state, &router_data, &context)- .await- .unwrap_or_else(|err| {- logger::warn!(- error = ?err,- "Failed to obtain an FRM access token; continuing without one"- );- None- });- }+ access_token::add_access_token_for_frm(&mut router_data);let pre_risk_check_request =payments_grpc::FrmServicePreRiskCheckRequest::foreign_try_from(&router_data)diff --git a/crates/router/src/core/unified_connector_service/frm.rs b/crates/router/src/core/unified_connector_service/frm.rsindex 384438523c..3f0fdb93ce 100644--- a/crates/router/src/core/unified_connector_service/frm.rs+++ b/crates/router/src/core/unified_connector_service/frm.rs@@ -4,8 +4,8 @@//! in-process. UCS-backed providers instead have their risk evaluation executed//! by the connector-service, which owns the provider-specific transformation.//!-//! This module holds what has no payments analogue: the access-token fetch for-//! bearer-authenticated providers and the lifecycle notification sender. The+//! This module holds what has no payments analogue: the lifecycle notification+//! sender. Access tokens are handled in `core::fraud_check::access_token`. The//! `RouterData ──▶ FrmServicePreRiskCheckRequest` builder lives with every other//! request builder in `transformers.rs`, the verdict handler with its siblings//! in the parent module, and the gRPC call itself in `core::fraud_check::gateway`.@@ -13,132 +13,19 @@use common_utils::{id_type, types::MinorUnit};use error_stack::ResultExt;use external_services::grpc_client::LineageIds;-use hyperswitch_domain_models::{- platform::Processor,- router_data::{AccessToken, RouterData},- router_flow_types::{fraud_check as frm_api, AccessTokenAuth},- router_request_types::{fraud_check::FraudCheckCheckoutData, AccessTokenRequestData},- router_response_types::fraud_check::FraudCheckResponseData,-};-use hyperswitch_interfaces::api::gateway;+use hyperswitch_domain_models::platform::Processor;use unified_connector_service_client::payments as payments_grpc;use super::{build_unified_connector_service_auth_metadata, get_ucs_client};use crate::{core::{errors::{self, RouterResult},- payments::{self, helpers::MerchantConnectorAccountType},+ payments::helpers::MerchantConnectorAccountType,},routes::SessionState,- services,- types::{api::FraudCheckConnectorData, transformers::ForeignTryFrom},+ types::transformers::ForeignTryFrom,};-/// Fetch (and cache) the OAuth token a bearer-authenticated FRM provider needs.-///-/// Kount's risk API is bearer-authenticated: the connector-service reads the token from-/// `state.access_token` and cannot mint one itself on the plain FRM service.-/// Reads Redis first, falling back to UCS `CreateServerAuthenticationToken`.-/// Providers using a static key (nSure) never reach this — `should_do_access_token`-/// is connector-side, so we gate on whether UCS returns a token at all.-#[cfg(feature = "v1")]-pub async fn get_frm_access_token(- state: &SessionState,- router_data: &RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>,- gateway_context: &payments::gateway::context::RouterGatewayContext,-) -> RouterResult<Option<AccessToken>> {- let processor = &gateway_context.processor;- let merchant_connector_account = &gateway_context.merchant_connector_account;- let merchant_id = processor.get_account().get_id();- let connector_name = router_data.connector.as_str();-- // Scope the cached token to the merchant connector account, the way the- // payments path does (`access_token::get_cached_access_token_for_ucs`).- // Keying on the connector name alone would make two accounts for the same- // FRM provider under one merchant share a token.- let merchant_connector_id = match merchant_connector_account {- MerchantConnectorAccountType::DbVal(mca) => Some(mca.get_id()),- MerchantConnectorAccountType::CacheVal(_) => None,- };-- let access_token_key = common_utils::access_token::get_default_access_token_key(- merchant_id,- merchant_connector_id- .as_ref()- .map(|id| id.get_string_repr().to_string())- .unwrap_or_else(|| connector_name.to_string()),- );-- if let Ok(Some(token)) = state.store.get_access_token(access_token_key.clone()).await {- router_env::logger::debug!(connector = connector_name, "FRM access token cache hit");- return Ok(Some(token));- }-- // Same gateway the payments path uses for `create_access_token`, so the- // FRM token fetch runs under `ucs_logging_wrapper_granular` and gets the- // same request/response/timing event. The router data is re-typed to the- // access-token flow first (as `add_access_token` does); the gateway picks- // the `PaymentVas` connector namespace from the FRM connector name.- let access_token_request =- AccessTokenRequestData::try_from(router_data.connector_auth_type.clone())- .attach_printable(- "Could not create FRM access token request from connector credentials",- )?;- let access_token_router_data =- payments::helpers::router_data_type_conversion::<_, AccessTokenAuth, _, _, _, AccessToken>(- router_data.clone(),- access_token_request,- Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),- );-- let connector = FraudCheckConnectorData::get_connector_by_name(connector_name)?;- let connector_integration: services::BoxedAccessTokenConnectorIntegrationInterface<- AccessTokenAuth,- AccessTokenRequestData,- AccessToken,- > = connector.connector.get_connector_integration();-- // The token fetch is a sub-step of the UCS pre-risk check, so it runs- // under the same gateway context that brought us here — same execution- // path, mode and account. Nothing to re-decide.- let token_result = gateway::execute_payment_gateway(- state,- connector_integration,- &access_token_router_data,- payments::CallConnectorAction::Trigger,- None,- None,- gateway_context.clone(),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("UCS create_access_token gateway call failed for FRM")?- .response;- match token_result {- Ok(token) => {- // Best-effort cache; a write failure only costs an extra token call.- let _ = super::set_access_token_for_ucs(- state,- processor,- connector_name,- token.clone(),- merchant_connector_id.as_ref(),- None,- )- .await;- Ok(Some(token))- }- Err(err) => {- router_env::logger::error!(- connector = connector_name,- error = ?err,- "UCS returned an error for the FRM access token"- );- Ok(None)- }- }-}-// Lifecycle notifications: the connector-service exposes four FRM events// (payment succeeded/failure, refund processed, chargeback received) on one// `NotifyConnector` RPC, differing only in event type and payload variant.@@ -196,10 +83,10 @@ pub struct FrmNotificationContext<'a> {/// and this handles auth metadata, `x-frm-connector` routing, and the gRPC/// call.///-/// Not yet wired to a call site. Before it is, bearer-authenticated providers-/// (Kount) need the access token threaded into `NotifyConnectorRequest.state`-/// via [`get_frm_access_token`], the way the pre-risk-check gateway does —-/// without it the notification reaches the provider unauthenticated.+/// No access token is sent. Before a bearer-authenticated provider is+/// onboarded, thread one into `NotifyConnectorRequest.state` (see+/// `core::fraud_check::access_token`) — without it the notification reaches+/// the provider unauthenticated.#[cfg(feature = "v1")]pub async fn call_unified_connector_service_for_frm_notification(state: &SessionState,diff --git a/crates/router/src/core/unified_connector_service/transformers.rs b/crates/router/src/core/unified_connector_service/transformers.rsindex 68fe608504..8484f26dc0 100644--- a/crates/router/src/core/unified_connector_service/transformers.rs+++ b/crates/router/src/core/unified_connector_service/transformers.rs@@ -11318,7 +11318,9 @@ implcustomer_info,payment_method,browser_info,- merchant_transaction_id: Some(router_data.attempt_id.clone()),+ // Carries the `fraud_check` row id (see the checkout flow), which+ // providers key their dedup/correlation on.+ merchant_transaction_id: Some(router_data.connector_request_reference_id.clone()),order_details,address: Some(payments_grpc::PaymentAddress::foreign_try_from(router_data.address.clone(),