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(payouts): check card payouts against the blocklist before the connector call (#14420)
Ayush Anandc65f807edb57
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex f492c42c70..a41ae6cd2d 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2559,6 +2559,7 @@ client_session_validation_enabled = { value = true, schema = { type = "boolean""webhooks.incoming_webhook_disabled_events" = { value = false, schema = { type = "boolean" }, description = "Whether a specific incoming webhook event is disabled for a given connector", change_reason = "Initial setup" }"payouts.max_auto_payout_retries" = { value = 0, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Maximum auto payout retries, differentiated by payout_retry_type dimension (single_connector or multi_connector)", change_reason = "Initial setup" }"payouts.payout_frm_call" = { value = false, schema = { type = "boolean" }, description = "Whether to call FRM for payouts", change_reason = "Initial setup" }+"payouts.payout_blocklist_guard" = { value = false, schema = { type = "boolean" }, description = "Whether to check card payouts against the blocklist and the profile's card blocking rules", change_reason = "Initial setup" }"payouts.payout_tracker_mapping" = { value = { frequencies = [[300,diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rsindex 9da88cabb9..9575efa140 100644--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs@@ -2419,6 +2419,27 @@ impl From<CardWithOptionalCVC> for EligibilityCard {}}+#[cfg(feature = "payouts")]+impl From<&api_models::payouts::CardPayout> for EligibilityCard {+ fn from(card: &api_models::payouts::CardPayout) -> Self {+ Self {+ card_number: card.card_number.clone(),+ card_exp_month: Some(card.expiry_month.clone()),+ card_exp_year: Some(card.expiry_year.clone()),+ card_cvc: None,+ card_issuer: None,+ card_network: card.card_network.clone(),+ card_type: None,+ card_issuing_country: None,+ card_issuing_country_code: None,+ bank_code: None,+ nick_name: None,+ card_holder_name: card.card_holder_name.clone(),+ co_badged_card_data: None,+ }+ }+}+impl From<Box<CardWithNetworkTokenDetails>> for EligibilityCard {fn from(card: Box<CardWithNetworkTokenDetails>) -> Self {Self::from(card.card_details)diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 033bd7d2b1..50266fec0c 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -533,6 +533,8 @@ pub mod superposition {pub const PAYOUT_FRM_CALL: &str = "payouts.payout_frm_call";/// Maximum number of card issuers a list request readspub const CARD_ISSUER_LIST_MAX_LIMIT: &str = "card_issuer.list_max_limit";+ /// Payout blocklist guard configuration key+ pub const PAYOUT_BLOCKLIST_GUARD: &str = "payouts.payout_blocklist_guard";}/// The value substituted for sensitive webhook header values in event retrieval responses.diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rsindex 5177b1c801..77fffc574e 100644--- a/crates/router/src/core/blocklist/utils.rs+++ b/crates/router/src/core/blocklist/utils.rs@@ -523,7 +523,7 @@ async fn delete_card_bin_blocklist_entry(})}-pub async fn should_payment_be_blocked(+pub async fn check_blocklist(state: &SessionState,processor: &domain::Processor,payment_method_data: &Option<domain::EligibilityPaymentMethodData>,@@ -607,12 +607,8 @@ pub async fn should_payment_be_blocked(.as_ref().is_some_and(|pmd| pmd.is_eligible_for_profile_config_blocklist()){- block_reason = should_payment_be_blocked_by_profile_config(- state,- payment_method_data,- business_profile,- )- .await?;+ block_reason =+ check_profile_blocking_config(state, payment_method_data, business_profile).await?;}Ok(block_reason)@@ -644,7 +640,7 @@ pub async fn is_blocklist_guard_enabled(/// blocklist entry (BIN kinds only — PAN-fingerprint entries cannot be matched from a/// BIN) for this merchant/profile, resolved with a single batched query. Merchant-wide/// entries (NULL `profile_id`) match every profile. DB errors are logged and treated as-/// not blocked, mirroring [`should_payment_be_blocked`].+/// not blocked, mirroring [`check_blocklist`].pub async fn get_blocked_bins(state: &SessionState,processor: &domain::Processor,@@ -683,7 +679,7 @@ whereF: Send + Clone,{let db = &state.store;- let block_reason = should_payment_be_blocked(+ let block_reason = check_blocklist(state,processor,&payment_data@@ -788,7 +784,7 @@ fn resolve_blocking_config_and_bin<'a>(}}-pub async fn should_payment_be_blocked_by_profile_config(+pub async fn check_profile_blocking_config(state: &SessionState,payment_method_data: &Option<domain::EligibilityPaymentMethodData>,business_profile: &domain::Profile,diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex c709864daf..ddc7ce7b49 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -1059,3 +1059,15 @@ config! {impl DatabaseBackedConfig for CardIssuerListMaxLimit {const KEY: &'static str = "card_issuer_list_max_limit";}++config! {+ superposition_key = PAYOUT_BLOCKLIST_GUARD,+ output = bool,+ default = false,+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ targeting_key = id_type::ProfileId+}++impl DatabaseBackedConfig for PayoutBlocklistGuard {+ const KEY: &'static str = "payout_blocklist_guard";+}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex fe0c35bde3..4beddea20a 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -14418,7 +14418,7 @@ impl EligibilityCheck for BlockListCheck {let payment_method_data = decrypted_payment_method_data.or_else(|| payment_elgibility_data.payment_method_data.clone());- let block_reason = blocklist_utils::should_payment_be_blocked(+ let block_reason = blocklist_utils::check_blocklist(state,platform.get_processor(),&payment_method_data,diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 68d98a1e30..2cd387576b 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -2,6 +2,8 @@use strum::IntoEnumIterator;pub mod access_token;pub mod gateway;+#[cfg(feature = "v1")]+pub mod guards;pub mod helpers;#[cfg(feature = "payout_retry")]pub mod retry;@@ -1509,6 +1511,37 @@ pub async fn call_connector_payout(if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() {helpers::fetch_payout_method_data(state, payout_data, connector_data, platform).await?;}++ #[cfg(feature = "v1")]+ let is_blocked = guards::is_payout_blocked(state, platform, payout_data, dimensions).await?;+ #[cfg(feature = "v2")]+ let is_blocked = false;++ if !is_blocked {+ Box::pin(run_payout_connector_flows(+ state,+ platform,+ header_payload,+ connector_data,+ payout_data,+ dimensions,+ ))+ .await?;+ }++ Ok(())+}++async fn run_payout_connector_flows(+ state: &SessionState,+ platform: &domain::Platform,+ header_payload: HeaderPayload,+ connector_data: &api::ConnectorData,+ payout_data: &mut PayoutData,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,+) -> RouterResult<()> {+ let payouts = &payout_data.payouts.to_owned();+// Fetch source_bank_data if not presentif payout_data.source_bank_data.is_none() {payout_data.source_bank_data = helpers::SourceBankDataOperation::get_temp_source_bank_data(diff --git a/crates/router/src/core/payouts/guards.rs b/crates/router/src/core/payouts/guards.rsnew file mode 100644index 0000000000..59d37ccf0e--- /dev/null+++ b/crates/router/src/core/payouts/guards.rs@@ -0,0 +1,219 @@+use std::str::FromStr;++use common_utils::payout_method_utils;+use error_stack::ResultExt;+use router_env::{instrument, logger, tracing};++use super::PayoutData;+use crate::{+ core::{+ blocklist::utils as blocklist_utils,+ configs::dimension_state,+ errors::{self, RouterResult},+ },+ routes::SessionState,+ types::{api::payouts, domain, storage},+};++const BLOCKLIST_ERROR_CODE: &str = "HE-03";++#[derive(Debug, Clone)]+pub enum PayoutGuardOutcome {+ Allow,+ Block(PayoutBlockDetails),+}++#[derive(Debug, Clone)]+pub struct PayoutBlockDetails {+ pub error_code: String,+ pub error_message: Option<String>,+}++#[async_trait::async_trait]+trait PayoutGuard {+ async fn should_run(+ &self,+ state: &SessionState,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ ) -> bool;++ async fn execute(+ &self,+ state: &SessionState,+ platform: &domain::Platform,+ payout_data: &PayoutData,+ ) -> RouterResult<PayoutGuardOutcome>;+}++struct BlocklistGuard;++#[async_trait::async_trait]+impl PayoutGuard for BlocklistGuard {+ async fn should_run(+ &self,+ state: &SessionState,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ ) -> bool {+ dimensions+ .get_payout_blocklist_guard(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await+ }++ async fn execute(+ &self,+ state: &SessionState,+ platform: &domain::Platform,+ payout_data: &PayoutData,+ ) -> RouterResult<PayoutGuardOutcome> {+ let block_reason = match get_blocklist_payment_method_data(payout_data) {+ Some(payment_method_data) => {+ blocklist_utils::check_blocklist(+ state,+ platform.get_processor(),+ &Some(payment_method_data),+ &payout_data.business_profile,+ )+ .await?+ }+ None => None,+ };++ Ok(block_reason.map_or(PayoutGuardOutcome::Allow, |reason| {+ logger::warn!(block_reason = ?reason, "Payout blocked by blocklist");+ PayoutGuardOutcome::Block(PayoutBlockDetails {+ error_code: BLOCKLIST_ERROR_CODE.to_string(),+ error_message: Some(reason.error_message()),+ })+ }))+ }+}++// A stored connector transfer method skips resolving the PAN, so fall back to the persisted BIN+fn get_blocklist_payment_method_data(+ payout_data: &PayoutData,+) -> Option<domain::EligibilityPaymentMethodData> {+ let card_from_payout_method_data =+ payout_data+ .payout_method_data+ .as_ref()+ .and_then(|payout_method_data| match payout_method_data {+ payouts::PayoutMethodData::Card(card) => Some(+ domain::EligibilityPaymentMethodData::Card(domain::EligibilityCard::from(card)),+ ),+ _ => None,+ });++ card_from_payout_method_data.or_else(|| {+ payout_data+ .payout_attempt+ .additional_payout_method_data+ .as_ref()+ .and_then(|additional_data| match additional_data {+ payout_method_utils::AdditionalPayoutMethodData::Card(card) => card+ .card_extended_bin+ .as_deref()+ .or(card.card_isin.as_deref())+ .and_then(|bin| cards::CardBin::from_str(bin).ok()),+ _ => None,+ })+ .map(|card_bin| {+ domain::EligibilityPaymentMethodData::CardBin(domain::EligibilityCardBin {+ card_bin,+ })+ })+ })+}++async fn run_guard<G: PayoutGuard + Sync>(+ guard: G,+ state: &SessionState,+ platform: &domain::Platform,+ payout_data: &PayoutData,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+) -> RouterResult<PayoutGuardOutcome> {+ match guard.should_run(state, dimensions).await {+ true => guard.execute(state, platform, payout_data).await,+ false => Ok(PayoutGuardOutcome::Allow),+ }+}++/// Runs the pre-connector payout guards and marks the payout failed if one blocks it.+/// Returns whether the payout was blocked. Expects `payout_method_data` to be resolved already.+#[instrument(skip_all)]+pub async fn is_payout_blocked(+ state: &SessionState,+ platform: &domain::Platform,+ payout_data: &mut PayoutData,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,+) -> RouterResult<bool> {+ let profile_dimensions =+ dimensions.with_profile_id(payout_data.business_profile.get_id().clone());++ let guard_outcome = run_guard(+ BlocklistGuard,+ state,+ platform,+ payout_data,+ &profile_dimensions,+ )+ .await?;++ match guard_outcome {+ PayoutGuardOutcome::Block(block_details) => {+ update_blocked_payout_tracker(state, platform, payout_data, block_details).await?;+ Ok(true)+ }+ PayoutGuardOutcome::Allow => Ok(false),+ }+}++async fn update_blocked_payout_tracker(+ state: &SessionState,+ platform: &domain::Platform,+ payout_data: &mut PayoutData,+ block_details: PayoutBlockDetails,+) -> RouterResult<()> {+ let db = &*state.store;+ let storage_scheme = platform.get_processor().get_account().storage_scheme;++ payout_data.payout_attempt = db+ .update_payout_attempt(+ &payout_data.payout_attempt,+ storage::PayoutAttemptUpdate::StatusUpdate {+ status: common_enums::PayoutStatus::Failed,+ error_code: Some(block_details.error_code),+ error_message: block_details.error_message,+ active_frm_id: None,+ is_eligible: Some(false),+ unified_code: None,+ unified_message: None,+ connector_eligibility_reference_id: None,+ connector_payout_id: None,+ payout_connector_metadata: None,+ },+ &payout_data.payouts,+ storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout attempt after pre-connector guard rejection")?;++ payout_data.payouts = db+ .update_payout(+ &payout_data.payouts,+ storage::PayoutsUpdate::StatusUpdate {+ status: common_enums::PayoutStatus::Failed,+ },+ &payout_data.payout_attempt,+ storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error updating payout after pre-connector guard rejection")?;++ Ok(())+}