Skip to content

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

feat(router): Add IP address only blocking in Card Testing Guard (#12553)

Anurag Thakurcb4f349f7ae3
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index fba4bdae8f..336069f3d2 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -16482,6 +16482,21 @@
"type": "integer",
"format": "int32",
"description": "Determines Redis Expiry for Card Testing Guard for profile"
+ },
+ "guest_ip_blocking_status": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CardTestingGuardStatus"
+ }
+ ],
+ "nullable": true
+ },
+ "guest_ip_blocking_threshold": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Determines the unsuccessful payment threshold for Guest IP Blocking for profile",
+ "default": 10,
+ "nullable": true
}
}
},
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index d13224ecd7..0055b4a444 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -10831,6 +10831,21 @@
"type": "integer",
"format": "int32",
"description": "Determines Redis Expiry for Card Testing Guard for profile"
+ },
+ "guest_ip_blocking_status": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CardTestingGuardStatus"
+ }
+ ],
+ "nullable": true
+ },
+ "guest_ip_blocking_threshold": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Determines the unsuccessful payment threshold for Guest IP Blocking for profile",
+ "default": 10,
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 3377019279..4cbdd07762 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -271,6 +271,11 @@ pub struct CardTestingGuardConfig {
pub customer_id_blocking_threshold: i32,
/// Determines Redis Expiry for Card Testing Guard for profile
pub card_testing_guard_expiry: i32,
+ /// Determines if Guest IP Blocking is enabled for profile
+ pub guest_ip_blocking_status: Option<CardTestingGuardStatus>,
+ /// Determines the unsuccessful payment threshold for Guest IP Blocking for profile
+ #[schema(default = 10)]
+ pub guest_ip_blocking_threshold: Option<i32>,
}
/// Configuration for payment method blocking based on card attributes
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 2bc6701132..ba37744b6d 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -214,6 +214,12 @@ pub const DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD: i32 = 5;
/// Default Card Testing Guard Redis Expiry in seconds
pub const DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS: i32 = 3600;
+/// Default status of Guest IP Blocking
+pub const DEFAULT_GUEST_IP_BLOCKING_STATUS: bool = false;
+
+/// Default Threshold for Guest IP Blocking
+pub const DEFAULT_GUEST_IP_BLOCKING_THRESHOLD: i32 = 10;
+
/// SOAP 1.1 Envelope Namespace
pub const SOAP_ENV_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/";
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index dec99d6d7d..5e4efef74f 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -820,6 +820,14 @@ pub struct SurchargeConnectorDetails {
common_utils::impl_to_sql_from_sql_json!(SurchargeConnectorDetails);
+fn default_guest_ip_blocking_status() -> bool {
+ common_utils::consts::DEFAULT_GUEST_IP_BLOCKING_STATUS
+}
+
+fn default_guest_ip_blocking_threshold() -> i32 {
+ common_utils::consts::DEFAULT_GUEST_IP_BLOCKING_THRESHOLD
+}
+
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct CardTestingGuardConfig {
@@ -830,6 +838,10 @@ pub struct CardTestingGuardConfig {
pub is_customer_id_blocking_enabled: bool,
pub customer_id_blocking_threshold: i32,
pub card_testing_guard_expiry: i32,
+ #[serde(default = "default_guest_ip_blocking_status")]
+ pub is_guest_ip_blocking_enabled: bool,
+ #[serde(default = "default_guest_ip_blocking_threshold")]
+ pub guest_ip_blocking_threshold: i32,
}
common_utils::impl_to_sql_from_sql_json!(CardTestingGuardConfig);
@@ -849,6 +861,8 @@ impl Default for CardTestingGuardConfig {
common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD,
card_testing_guard_expiry:
common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS,
+ is_guest_ip_blocking_enabled: common_utils::consts::DEFAULT_GUEST_IP_BLOCKING_STATUS,
+ guest_ip_blocking_threshold: common_utils::consts::DEFAULT_GUEST_IP_BLOCKING_THRESHOLD,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/card_testing_guard_data.rs b/crates/hyperswitch_domain_models/src/card_testing_guard_data.rs
index 329f89b946..924a7619b1 100644
--- a/crates/hyperswitch_domain_models/src/card_testing_guard_data.rs
+++ b/crates/hyperswitch_domain_models/src/card_testing_guard_data.rs
@@ -3,10 +3,12 @@ use serde::{self, Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct CardTestingGuardData {
pub is_card_ip_blocking_enabled: bool,
- pub card_ip_blocking_cache_key: String,
+ pub card_ip_blocking_cache_key: Option<String>,
pub is_guest_user_card_blocking_enabled: bool,
- pub guest_user_card_blocking_cache_key: String,
+ pub guest_user_card_blocking_cache_key: Option<String>,
pub is_customer_id_blocking_enabled: bool,
- pub customer_id_blocking_cache_key: String,
+ pub customer_id_blocking_cache_key: Option<String>,
pub card_testing_guard_expiry: i32,
+ pub is_guest_ip_blocking_enabled: bool,
+ pub guest_ip_blocking_cache_key: Option<String>,
}
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 1dc078d1c8..9cbee34053 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -91,6 +91,8 @@ pub const GUEST_USER_CARD_BLOCKING_CACHE_KEY_PREFIX: &str = "GUEST_USER_CARD_BLO
pub const CUSTOMER_ID_BLOCKING_PREFIX: &str = "CUSTOMER_ID_BLOCKING";
+pub const GUEST_IP_BLOCKING_CACHE_KEY_PREFIX: &str = "GUEST_IP_BLOCKING";
+
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify";
#[cfg(feature = "olap")]
diff --git a/crates/router/src/core/card_testing_guard/utils.rs b/crates/router/src/core/card_testing_guard/utils.rs
index e27dfdbf71..2b1309f4d8 100644
--- a/crates/router/src/core/card_testing_guard/utils.rs
+++ b/crates/router/src/core/card_testing_guard/utils.rs
@@ -26,72 +26,88 @@ pub async fn validate_card_testing_guard_checks(
Some(card_testing_guard_config) => {
let fingerprint = generate_fingerprint(card_number, business_profile).await?;
- let card_testing_guard_expiry = card_testing_guard_config.card_testing_guard_expiry;
-
- let mut card_ip_blocking_cache_key = String::new();
- let mut guest_user_card_blocking_cache_key = String::new();
- let mut customer_id_blocking_cache_key = String::new();
-
- if card_testing_guard_config.is_card_ip_blocking_enabled {
- if let Some(browser_info) = browser_info {
- #[cfg(feature = "v1")]
- {
- let browser_info =
- serde_json::from_value::<BrowserInformation>(browser_info.clone())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("could not parse browser_info")?;
-
- if let Some(browser_info_ip) = browser_info.ip_address {
- card_ip_blocking_cache_key =
- helpers::validate_card_ip_blocking_for_business_profile(
- state,
- browser_info_ip,
- fingerprint.clone(),
- card_testing_guard_config,
- )
- .await?;
- }
- }
+ let ip_address = extract_ip_from_browser_info(browser_info);
- #[cfg(feature = "v2")]
- {
- if let Some(browser_info_ip) = browser_info.ip_address {
- card_ip_blocking_cache_key =
- helpers::validate_card_ip_blocking_for_business_profile(
- state,
- browser_info_ip,
- fingerprint.clone(),
- card_testing_guard_config,
- )
- .await?;
- }
+ let card_ip_blocking_cache_key =
+ if card_testing_guard_config.is_card_ip_blocking_enabled {
+ match ip_address {
+ Some(ip) => Some(
+ helpers::validate_card_ip_blocking_for_business_profile(
+ state,
+ ip,
+ fingerprint.clone(),
+ card_testing_guard_config,
+ )
+ .await?,
+ ),
+ None => None,
}
- }
- }
+ } else {
+ None
+ };
- if card_testing_guard_config.is_guest_user_card_blocking_enabled {
- guest_user_card_blocking_cache_key =
- helpers::validate_guest_user_card_blocking_for_business_profile(
- state,
- fingerprint.clone(),
- customer_id.clone(),
- card_testing_guard_config,
+ let guest_user_card_blocking_cache_key =
+ if card_testing_guard_config.is_guest_user_card_blocking_enabled {
+ Some(
+ helpers::validate_guest_user_card_blocking_for_business_profile(
+ state,
+ fingerprint.clone(),
+ customer_id.clone(),
+ card_testing_guard_config,
+ )
+ .await?,
)
- .await?;
- }
+ } else {
+ None
+ };
- if card_testing_guard_config.is_customer_id_blocking_enabled {
- if let Some(customer_id) = customer_id.clone() {
- customer_id_blocking_cache_key =
- helpers::validate_customer_id_blocking_for_business_profile(
+ let customer_id_blocking_cache_key =
+ if card_testing_guard_config.is_customer_id_blocking_enabled {
+ match customer_id.clone() {
+ Some(cid) => Some(
+ helpers::validate_customer_id_blocking_for_business_profile(
+ state,
+ cid,
+ business_profile.get_id(),
+ card_testing_guard_config,
+ )
+ .await?,
+ ),
+ None => None,
+ }
+ } else {
+ None
+ };
+
+ let guest_ip_blocking_cache_key = if card_testing_guard_config
+ .is_guest_ip_blocking_enabled
+ && customer_id.is_none()
+ {
+ match ip_address {
+ Some(ip) => {
+ match helpers::validate_guest_ip_blocking_for_business_profile(
state,
- customer_id.clone(),
+ ip,
business_profile.get_id(),
card_testing_guard_config,
)
- .await?;
+ .await
+ {
+ Ok(cache_key) => Ok(Some(cache_key)),
+ Err(err) => match err.current_context() {
+ errors::ApiErrorResponse::PreconditionFailed { .. } => Err(err),
+ _ => {
+ logger::error!("Guest IP blocking validation error: {:?}", err);
+ Ok(None)
+ }
+ },
+ }
+ }
+ None => Ok(None),
}
- }
+ } else {
+ Ok(None)
+ }?;
Ok(Some(CardTestingGuardData {
is_card_ip_blocking_enabled: card_testing_guard_config.is_card_ip_blocking_enabled,
@@ -102,13 +118,42 @@ pub async fn validate_card_testing_guard_checks(
is_customer_id_blocking_enabled: card_testing_guard_config
.is_customer_id_blocking_enabled,
customer_id_blocking_cache_key,
- card_testing_guard_expiry,
+ card_testing_guard_expiry: card_testing_guard_config.card_testing_guard_expiry,
+ is_guest_ip_blocking_enabled: card_testing_guard_config
+ .is_guest_ip_blocking_enabled,
+ guest_ip_blocking_cache_key,
}))
}
None => Ok(None),
}
}
+fn extract_ip_from_browser_info(
+ #[cfg(feature = "v1")] browser_info: Option<&serde_json::Value>,
+ #[cfg(feature = "v2")] browser_info: Option<&BrowserInformation>,
+) -> Option<std::net::IpAddr> {
+ #[cfg(feature = "v1")]
+ {
+ browser_info.and_then(|info| {
+ match serde_json::from_value::<BrowserInformation>(info.clone()) {
+ Ok(b) => b.ip_address,
+ Err(err) => {
+ logger::error!(
+ "Failed to deserialize browser_info for IP extraction: {:?}",
+ err
+ );
+ None
+ }
+ }
+ })
+ }
+
+ #[cfg(feature = "v2")]
+ {
+ browser_info.and_then(|b| b.ip_address)
+ }
+}
+
pub async fn generate_fingerprint(
card_number: cards::CardNumber,
business_profile: &domain::Profile,
@@ -145,46 +190,75 @@ pub async fn generate_fingerprint(
pub async fn increment_blocked_count_in_cache(
state: &SessionState,
card_testing_guard_data: Option<CardTestingGuardData>,
-) -> RouterResult<()> {
- if let Some(card_testing_guard_data) = card_testing_guard_data.clone() {
- if card_testing_guard_data.is_card_ip_blocking_enabled
- && !card_testing_guard_data
- .card_ip_blocking_cache_key
- .is_empty()
- {
- let _ = services::card_testing_guard::increment_blocked_count_in_cache(
- state,
- &card_testing_guard_data.card_ip_blocking_cache_key,
- card_testing_guard_data.card_testing_guard_expiry.into(),
- )
- .await;
+) {
+ if let Some(card_testing_guard_data) = card_testing_guard_data {
+ if card_testing_guard_data.is_card_ip_blocking_enabled {
+ if let Some(ref cache_key) = card_testing_guard_data.card_ip_blocking_cache_key {
+ if let Err(err) = services::card_testing_guard::increment_blocked_count_in_cache(
+ state,
+ cache_key,
+ card_testing_guard_data.card_testing_guard_expiry.into(),
+ )
+ .await
+ {
+ logger::error!(
+ "Failed to increment card IP blocked count in cache: {:?}",
+ err
+ );
+ }
+ }
}
- if card_testing_guard_data.is_guest_user_card_blocking_enabled
- && !card_testing_guard_data
- .guest_user_card_blocking_cache_key
- .is_empty()
- {
- let _ = services::card_testing_guard::increment_blocked_count_in_cache(
- state,
- &card_testing_guard_data.guest_user_card_blocking_cache_key,
- card_testing_guard_data.card_testing_guard_expiry.into(),
- )
- .await;
+ if card_testing_guard_data.is_guest_user_card_blocking_enabled {
+ if let Some(ref cache_key) = card_testing_guard_data.guest_user_card_blocking_cache_key
+ {
+ if let Err(err) = services::card_testing_guard::increment_blocked_count_in_cache(
+ state,
+ cache_key,
+ card_testing_guard_data.card_testing_guard_expiry.into(),
+ )
+ .await
+ {
+ logger::error!(
+ "Failed to increment guest user card blocked count in cache: {:?}",
+ err
+ );
+ }
+ }
}
- if card_testing_guard_data.is_customer_id_blocking_enabled
- && !card_testing_guard_data
- .customer_id_blocking_cache_key
- .is_empty()
- {
- let _ = services::card_testing_guard::increment_blocked_count_in_cache(
- state,
- &card_testing_guard_data.customer_id_blocking_cache_key,
- card_testing_guard_data.card_testing_guard_expiry.into(),
- )
- .await;
+ if card_testing_guard_data.is_customer_id_blocking_enabled {
+ if let Some(ref cache_key) = card_testing_guard_data.customer_id_blocking_cache_key {
+ if let Err(err) = services::card_testing_guard::increment_blocked_count_in_cache(
+ state,
+ cache_key,
+ card_testing_guard_data.card_testing_guard_expiry.into(),
+ )
+ .await
+ {
+ logger::error!(
+ "Failed to increment customer ID blocked count in cache: {:?}",
+ err
+ );
+ }
+ }
+ }
+
+ if card_testing_guard_data.is_guest_ip_blocking_enabled {
+ if let Some(ref cache_key) = card_testing_guard_data.guest_ip_blocking_cache_key {
+ if let Err(err) = services::card_testing_guard::increment_blocked_count_in_cache(
+ state,
+ cache_key,
+ card_testing_guard_data.card_testing_guard_expiry.into(),
+ )
+ .await
+ {
+ logger::error!(
+ "Failed to increment guest IP blocked count in cache: {:?}",
+ err
+ );
+ }
+ }
}
}
- Ok(())
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 13fe02536e..63c460417e 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1673,6 +1673,30 @@ pub async fn validate_customer_id_blocking_for_business_profile(
validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await
}
+pub async fn validate_guest_ip_blocking_for_business_profile(
+ state: &SessionState,
+ client_ip: IpAddr,
+ profile_id: &id_type::ProfileId,
+ card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig,
+) -> RouterResult<String> {
+ let normalized_ip = match client_ip {
+ IpAddr::V4(v4) => v4.to_string(),
+ IpAddr::V6(v6) => v6.to_canonical().to_string(),
+ }
+ .replace(':', "-");
+
+ let cache_key = format!(
+ "{}_{}_{}",
+ consts::GUEST_IP_BLOCKING_CACHE_KEY_PREFIX,
+ profile_id.get_string_repr(),
+ normalized_ip
+ );
+
+ let unsuccessful_payment_threshold = card_testing_guard_config.guest_ip_blocking_threshold;
+
+ validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await
+}
+
pub async fn validate_blocking_threshold(
state: &SessionState,
unsuccessful_payment_threshold: i32,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index e17a79b961..9a610f12a1 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -3021,7 +3021,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
});
if payment_data.payment_attempt.status == enums::AttemptStatus::Failure {
- let _ = card_testing_guard_utils::increment_blocked_count_in_cache(
+ card_testing_guard_utils::increment_blocked_count_in_cache(
state,
payment_data.card_testing_guard_data.clone(),
)
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 73fd625234..e33075e577 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -2249,6 +2249,14 @@ impl ForeignFrom<api_models::admin::CardTestingGuardConfig>
},
customer_id_blocking_threshold: item.customer_id_blocking_threshold,
card_testing_guard_expiry: item.card_testing_guard_expiry,
+ is_guest_ip_blocking_enabled: match item.guest_ip_blocking_status {
+ Some(api_models::admin::CardTestingGuardStatus::Enabled) => true,
+ Some(api_models::admin::CardTestingGuardStatus::Disabled) => false,
+ None => common_utils::consts::DEFAULT_GUEST_IP_BLOCKING_STATUS,
+ },
+ guest_ip_blocking_threshold: item
+ .guest_ip_blocking_threshold
+ .unwrap_or(common_utils::consts::DEFAULT_GUEST_IP_BLOCKING_THRESHOLD),
}
}
}
@@ -2274,6 +2282,11 @@ impl ForeignFrom<diesel_models::business_profile::CardTestingGuardConfig>
},
customer_id_blocking_threshold: item.customer_id_blocking_threshold,
card_testing_guard_expiry: item.card_testing_guard_expiry,
+ guest_ip_blocking_status: Some(match item.is_guest_ip_blocking_enabled {
+ true => api_models::admin::CardTestingGuardStatus::Enabled,
+ false => api_models::admin::CardTestingGuardStatus::Disabled,
+ }),
+ guest_ip_blocking_threshold: Some(item.guest_ip_blocking_threshold),
}
}
}