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(router): Implement rate limiting for unverified webhooks (#14587)
Anurag Thakurc996afb57a64
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex 6915424701..fc7808c4b1 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2557,6 +2557,11 @@ client_session_validation_enabled = { value = true, schema = { type = "boolean""payments.implicit_customer_update" = { value = false, schema = { type = "boolean" }, description = "Whether to implicitly update customer details on payment", change_reason = "Initial setup" }"payments.block_implicit_customer_creation" = { value = false, schema = { type = "boolean" }, description = "Whether payments must reject implicit creation of a missing customer for an organization", change_reason = "Decouple implicit customer creation from PM modular eligibility" }"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" }+"webhooks.unverified_webhook_rate_limit_enabled" = { value = false, schema = { type = "boolean" }, description = "Whether unverified incoming webhooks are rate limited (reject with 429 when a limit is reached)", change_reason = "Unverified webhook rate limiting" }+"webhooks.unverified_webhook_rate_limit_window_in_secs" = { value = 60, schema = { maximum = 4294967295, minimum = 1, type = "integer" }, description = "Fixed window, in seconds, over which unverified incoming webhooks are counted", change_reason = "Unverified webhook rate limiting" }+"webhooks.unverified_webhook_merchant_rate_limit" = { value = 60, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Maximum unverified incoming webhooks per merchant per window, 0 disables the merchant level", change_reason = "Unverified webhook rate limiting" }+"webhooks.unverified_webhook_profile_rate_limit" = { value = 0, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Maximum unverified incoming webhooks per profile per window, 0 disables the profile level", change_reason = "Unverified webhook rate limiting" }+"webhooks.unverified_webhook_merchant_connector_account_rate_limit" = { value = 0, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Maximum unverified incoming webhooks per merchant connector account per window, 0 disables the merchant connector account level", change_reason = "Unverified webhook rate limiting" }"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" }@@ -3291,6 +3296,7 @@ mandate_type = { position = 6, schema = { enum = ["mandate","non_mandate",], type = "string" }, type = "REGULAR" }+merchant_connector_id = { position = 21, schema = { pattern = ".*", type = "string" }, type = "REGULAR", description = "Merchant connector account id", change_reason = "Unverified webhook rate limiting" }method = { position = 20, schema = { type = "string" }, type = "REGULAR", description = "HTTP request method (Deja recording sampler context)", change_reason = "Deja recording sampler" }organization_id = { position = 11, schema = { pattern = ".*", type = "string" }, type = "REGULAR" }path = { position = 19, schema = { type = "string" }, type = "REGULAR", description = "HTTP request path (basis of the deja_dimension cohort)", change_reason = "Deja recording sampler" }diff --git a/crates/api_models/src/errors/actix.rs b/crates/api_models/src/errors/actix.rsindex 5c05b6e80d..9e920eaa96 100644--- a/crates/api_models/src/errors/actix.rs+++ b/crates/api_models/src/errors/actix.rs@@ -10,6 +10,7 @@ impl actix_web::ResponseError for ApiErrorResponse {Self::ForbiddenPrivateResource(_) => StatusCode::NOT_FOUND,Self::Conflict(_) => StatusCode::CONFLICT,Self::Gone(_) => StatusCode::GONE,+ Self::TooManyRequests(_) => StatusCode::TOO_MANY_REQUESTS,Self::Unprocessable(_) => StatusCode::UNPROCESSABLE_ENTITY,Self::InternalServerError(_) => StatusCode::INTERNAL_SERVER_ERROR,Self::NotImplemented(_) => StatusCode::NOT_IMPLEMENTED,diff --git a/crates/api_models/src/errors/types.rs b/crates/api_models/src/errors/types.rsindex abe94a8d6f..a63a8cfe1b 100644--- a/crates/api_models/src/errors/types.rs+++ b/crates/api_models/src/errors/types.rs@@ -94,6 +94,7 @@ pub enum ApiErrorResponse {ForbiddenPrivateResource(ApiError),Conflict(ApiError),Gone(ApiError),+ TooManyRequests(ApiError),Unprocessable(ApiError),InternalServerError(ApiError),NotImplemented(ApiError),@@ -124,6 +125,7 @@ impl ApiErrorResponse {| Self::ForbiddenPrivateResource(i)| Self::Conflict(i)| Self::Gone(i)+ | Self::TooManyRequests(i)| Self::Unprocessable(i)| Self::InternalServerError(i)| Self::NotImplemented(i)@@ -142,6 +144,7 @@ impl ApiErrorResponse {| Self::ForbiddenPrivateResource(i)| Self::Conflict(i)| Self::Gone(i)+ | Self::TooManyRequests(i)| Self::Unprocessable(i)| Self::InternalServerError(i)| Self::NotImplemented(i)@@ -160,6 +163,7 @@ impl ApiErrorResponse {| Self::ForbiddenPrivateResource(_)| Self::Conflict(_)| Self::Gone(_)+ | Self::TooManyRequests(_)| Self::Unprocessable(_)| Self::NotImplemented(_)| Self::MethodNotAllowed(_)diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rsindex d120643c9a..689bb1bbb2 100644--- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs@@ -334,6 +334,8 @@ pub enum ApiErrorResponse {WebhookUnprocessableEntity,#[error(error_type = ErrorType::InvalidRequestError, code = "WE_06", message = "Merchant Secret set my merchant for webhook source verification is invalid")]WebhookInvalidMerchantSecret,+ #[error(error_type = ErrorType::InvalidRequestError, code = "WE_07", message = "Too many unverified webhooks received")]+ WebhookRateLimited,#[error(error_type = ErrorType::ServerNotAvailable, code = "IE", message = "{reason} as data mismatched for {field_names}")]IntegrityCheckFailed {payment_id: Option<common_utils::id_type::PaymentId>,@@ -742,6 +744,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponSelf::WebhookInvalidMerchantSecret => {AER::BadRequest(ApiError::new("WE", 6, "Merchant Secret set for webhook source verification is invalid", None))}+ Self::WebhookRateLimited => {+ AER::TooManyRequests(ApiError::new("WE", 7, "Too many unverified webhooks received", None))+ }Self::IntegrityCheckFailed {reason,field_names,diff --git a/crates/redis_interface/src/constant.rs b/crates/redis_interface/src/constant.rsindex 5176e9f0ff..3f2bca16c3 100644--- a/crates/redis_interface/src/constant.rs+++ b/crates/redis_interface/src/constant.rs@@ -7,6 +7,8 @@pub mod redis_rs_commands {pub const REDIS_COMMAND_SET: &str = "SET";pub const REDIS_COMMAND_GET: &str = "GET";+ pub const REDIS_COMMAND_INCR: &str = "INCR";+ pub const REDIS_COMMAND_DECR: &str = "DECR";pub const REDIS_COMMAND_HSCAN: &str = "HSCAN";pub const REDIS_COMMAND_SCAN: &str = "SCAN";diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rsindex f230c51e6f..bf9e4d00b1 100644--- a/crates/redis_interface/src/errors.rs+++ b/crates/redis_interface/src/errors.rs@@ -83,6 +83,10 @@ pub enum RedisError {PopListElementsFailed,#[error("Failed to increment hash field in Redis")]IncrementHashFieldFailed,+ #[error("Failed to increment key in Redis")]+ IncrementKeyFailed,+ #[error("Failed to decrement key in Redis")]+ DecrementKeyFailed,#[error("Failed to evaluate Lua script in Redis")]ScriptExecutionFailed,}diff --git a/crates/redis_interface/src/metrics.rs b/crates/redis_interface/src/metrics.rsindex 42c93c4a46..990cd26135 100644--- a/crates/redis_interface/src/metrics.rs+++ b/crates/redis_interface/src/metrics.rs@@ -33,6 +33,8 @@ pub(crate) enum RedisOperation {SetMultipleKeysIfNotExist,SetKeyIfNotExistsWithExpiry,SetKeyIfNotExistsAndGetValue,+ IncrementKeyWithExpiry,+ DecrementKeyWithExpiry,GetKey,GetMultipleKeys,Exists,diff --git a/crates/redis_interface/src/module/fred/commands.rs b/crates/redis_interface/src/module/fred/commands.rsindex 8a443297d9..be96d5949a 100644--- a/crates/redis_interface/src/module/fred/commands.rs+++ b/crates/redis_interface/src/module/fred/commands.rs@@ -2427,4 +2427,108 @@ impl super::RedisConnectionWithContext {.attach_printable("Unexpected result from SET NX operation"),}}++ /// Increments `key` by one and returns the value after the increment.+ ///+ /// If the key does not exist, it is first created at 0 with `ttl_in_secs` as its expiry, so a key+ /// written by this command always has an expiry. A key that already exists keeps the expiry it+ /// has. The two commands run in one transaction on the single key, so the key cannot expire+ /// between them and be recreated by the increment without an expiry.+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn increment_key_with_expiry(+ &self,+ key: &RedisKey,+ ttl_in_secs: i64,+ ) -> CustomResult<i64, errors::RedisError> {+ let redis_key = key.tenant_aware_key(&self.redis_conn);+ let trx = self.get_transaction();++ trx.set::<(), _, _>(+ &redis_key,+ 0,+ Some(Expiration::EX(ttl_in_secs)),+ Some(SetOptions::NX),+ false,+ )+ .await+ .change_context(errors::RedisError::IncrementKeyFailed)+ .attach_printable("Failed to queue set command")?;++ trx.incr::<(), _>(&redis_key)+ .await+ .change_context(errors::RedisError::IncrementKeyFailed)+ .attach_printable("Failed to queue increment command")?;++ let mut results: Vec<RedisValue> = track_redis_call(+ self.request_id.as_deref(),+ self.redis_conn.event_emitter.as_ref(),+ RedisOperation::IncrementKeyWithExpiry,+ trx.exec(true),+ )+ .await+ .change_context(errors::RedisError::IncrementKeyFailed)+ .attach_printable("Failed to execute the redis transaction")?;++ // The results are the SET reply followed by the INCR reply+ let value_after_increment = results+ .pop()+ .ok_or(errors::RedisError::IncrementKeyFailed)+ .attach_printable("Got unexpected number of results from transaction")?;++ i64::from_value(value_after_increment)+ .change_context(errors::RedisError::IncrementKeyFailed)+ .attach_printable("Failed to convert from redis value")+ }++ /// Decrements `key` by one and returns the value after the decrement.+ ///+ /// If the key does not exist, it is first created at 0 with `ttl_in_secs` as its expiry, so a key+ /// written by this command always has an expiry. A key that already exists keeps the expiry it+ /// has. The two commands run in one transaction on the single key, so the key cannot expire+ /// between them and be recreated by the decrement without an expiry.+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn decrement_key_with_expiry(+ &self,+ key: &RedisKey,+ ttl_in_secs: i64,+ ) -> CustomResult<i64, errors::RedisError> {+ let redis_key = key.tenant_aware_key(&self.redis_conn);+ let trx = self.get_transaction();++ trx.set::<(), _, _>(+ &redis_key,+ 0,+ Some(Expiration::EX(ttl_in_secs)),+ Some(SetOptions::NX),+ false,+ )+ .await+ .change_context(errors::RedisError::DecrementKeyFailed)+ .attach_printable("Failed to queue set command")?;++ trx.decr::<(), _>(&redis_key)+ .await+ .change_context(errors::RedisError::DecrementKeyFailed)+ .attach_printable("Failed to queue decrement command")?;++ let mut results: Vec<RedisValue> = track_redis_call(+ self.request_id.as_deref(),+ self.redis_conn.event_emitter.as_ref(),+ RedisOperation::DecrementKeyWithExpiry,+ trx.exec(true),+ )+ .await+ .change_context(errors::RedisError::DecrementKeyFailed)+ .attach_printable("Failed to execute the redis transaction")?;++ // The results are the SET reply followed by the DECR reply+ let value_after_decrement = results+ .pop()+ .ok_or(errors::RedisError::DecrementKeyFailed)+ .attach_printable("Got unexpected number of results from transaction")?;++ i64::from_value(value_after_decrement)+ .change_context(errors::RedisError::DecrementKeyFailed)+ .attach_printable("Failed to convert from redis value")+ }}diff --git a/crates/redis_interface/src/module/redis_rs/commands.rs b/crates/redis_interface/src/module/redis_rs/commands.rsindex 63fb8f70dd..26fc2fc4ef 100644--- a/crates/redis_interface/src/module/redis_rs/commands.rs+++ b/crates/redis_interface/src/module/redis_rs/commands.rs@@ -27,7 +27,8 @@ use super::types::redis_value_to_option_string;use crate::{constant::redis_rs_commands::{REDIS_ARG_COUNT, REDIS_ARG_EX, REDIS_ARG_MATCH, REDIS_ARG_NX, REDIS_ARG_TYPE,- REDIS_COMMAND_GET, REDIS_COMMAND_HSCAN, REDIS_COMMAND_SCAN, REDIS_COMMAND_SET,+ REDIS_COMMAND_DECR, REDIS_COMMAND_GET, REDIS_COMMAND_HSCAN, REDIS_COMMAND_INCR,+ REDIS_COMMAND_SCAN, REDIS_COMMAND_SET,},errors,metrics::{track_redis_call, RedisOperation},@@ -1806,4 +1807,90 @@ impl super::RedisConnectionWithContext {SetnxReply::KeyNotSet => SetGetReply::ValueExists(actual_value),})}++ /// Increments `key` by one and returns the value after the increment.+ ///+ /// If the key does not exist, it is first created at 0 with `ttl_in_secs` as its expiry, so a key+ /// written by this command always has an expiry. A key that already exists keeps the expiry it+ /// has. The two commands run in one transaction on the single key, so the key cannot expire+ /// between them and be recreated by the increment without an expiry.+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn increment_key_with_expiry(+ &self,+ key: &RedisKey,+ ttl_in_secs: i64,+ ) -> CustomResult<i64, errors::RedisError> {+ let redis_key = key.tenant_aware_key(&self.redis_conn);+ let mut conn = self.redis_conn.pool.clone();++ // Build an atomic pipeline (MULTI/EXEC)+ let mut pipe = redis::pipe();+ pipe.atomic();++ // SET key 0 EX ttl NX, its reply is left out of the results+ pipe.cmd(REDIS_COMMAND_SET)+ .arg(&redis_key)+ .arg(0)+ .arg(REDIS_ARG_EX)+ .arg(ttl_in_secs)+ .arg(REDIS_ARG_NX)+ .ignore();++ pipe.cmd(REDIS_COMMAND_INCR).arg(&redis_key);++ let (value_after_increment,): (i64,) = track_redis_call(+ self.request_id.as_deref(),+ self.redis_conn.event_emitter.as_ref(),+ RedisOperation::IncrementKeyWithExpiry,+ pipe.query_async(&mut conn),+ )+ .await+ .change_context(errors::RedisError::IncrementKeyFailed)+ .attach_printable("Failed to execute the redis transaction")?;++ Ok(value_after_increment)+ }++ /// Decrements `key` by one and returns the value after the decrement.+ ///+ /// If the key does not exist, it is first created at 0 with `ttl_in_secs` as its expiry, so a key+ /// written by this command always has an expiry. A key that already exists keeps the expiry it+ /// has. The two commands run in one transaction on the single key, so the key cannot expire+ /// between them and be recreated by the decrement without an expiry.+ #[instrument(level = "DEBUG", skip(self))]+ pub async fn decrement_key_with_expiry(+ &self,+ key: &RedisKey,+ ttl_in_secs: i64,+ ) -> CustomResult<i64, errors::RedisError> {+ let redis_key = key.tenant_aware_key(&self.redis_conn);+ let mut conn = self.redis_conn.pool.clone();++ // Build an atomic pipeline (MULTI/EXEC)+ let mut pipe = redis::pipe();+ pipe.atomic();++ // SET key 0 EX ttl NX, its reply is left out of the results+ pipe.cmd(REDIS_COMMAND_SET)+ .arg(&redis_key)+ .arg(0)+ .arg(REDIS_ARG_EX)+ .arg(ttl_in_secs)+ .arg(REDIS_ARG_NX)+ .ignore();++ pipe.cmd(REDIS_COMMAND_DECR).arg(&redis_key);++ let (value_after_decrement,): (i64,) = track_redis_call(+ self.request_id.as_deref(),+ self.redis_conn.event_emitter.as_ref(),+ RedisOperation::DecrementKeyWithExpiry,+ pipe.query_async(&mut conn),+ )+ .await+ .change_context(errors::RedisError::DecrementKeyFailed)+ .attach_printable("Failed to execute the redis transaction")?;++ Ok(value_after_decrement)+ }}diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rsindex c98f1c4282..63ebda9d5c 100644--- a/crates/router/src/compatibility/stripe/errors.rs+++ b/crates/router/src/compatibility/stripe/errors.rs@@ -679,9 +679,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {| errors::ApiErrorResponse::WebhookProcessingFailure| errors::ApiErrorResponse::WebhookAuthenticationFailed| errors::ApiErrorResponse::WebhookUnprocessableEntity- | errors::ApiErrorResponse::WebhookInvalidMerchantSecret => {- Self::WebhookProcessingError- }+ | errors::ApiErrorResponse::WebhookInvalidMerchantSecret+ | errors::ApiErrorResponse::WebhookRateLimited => Self::WebhookProcessingError,errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => {Self::PaymentMethodUnactivated}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex b52c7807d8..40d91c7809 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -529,6 +529,21 @@ pub mod superposition {pub const THREEDS_ROUTING_REGION_UAS: &str = "routing.threeds_routing_region_uas";/// disabled webhook events configuration key per merchant and connectorpub const INCOMING_WEBHOOK_DISABLED_EVENTS: &str = "webhooks.incoming_webhook_disabled_events";+ /// Whether unverified webhook rate limiting is enabled, defaults to `false`+ pub const UNVERIFIED_WEBHOOK_RATE_LIMIT_ENABLED: &str =+ "webhooks.unverified_webhook_rate_limit_enabled";+ /// Fixed window, in seconds, over which unverified webhooks are counted+ pub const UNVERIFIED_WEBHOOK_RATE_LIMIT_WINDOW_IN_SECS: &str =+ "webhooks.unverified_webhook_rate_limit_window_in_secs";+ /// Maximum unverified webhooks per merchant per window, defaults to 60, `0` disables the merchant level+ pub const UNVERIFIED_WEBHOOK_MERCHANT_RATE_LIMIT: &str =+ "webhooks.unverified_webhook_merchant_rate_limit";+ /// Maximum unverified webhooks per profile per window, `0` disables the profile level+ pub const UNVERIFIED_WEBHOOK_PROFILE_RATE_LIMIT: &str =+ "webhooks.unverified_webhook_profile_rate_limit";+ /// Maximum unverified webhooks per merchant connector account per window, `0` disables the merchant connector account level+ pub const UNVERIFIED_WEBHOOK_MERCHANT_CONNECTOR_ACCOUNT_RATE_LIMIT: &str =+ "webhooks.unverified_webhook_merchant_connector_account_rate_limit";/// save wallet decrypted data in lockerpub const SAVE_WALLET_DECRYPTED_DATA: &str = "vaulting.save_wallet_decrypted_data";/// checkout sdk configurationdiff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex afb6b01966..914fa7e41c 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -966,6 +966,87 @@ impl DatabaseBackedConfig for IncomingWebhookDisabledEvents {}}+config! {+ superposition_key = UNVERIFIED_WEBHOOK_RATE_LIMIT_ENABLED,+ output = bool,+ default = false,+ requires = dimension_state::DimensionsWithMerchantConnectorAccount,+ targeting_key = id_type::MerchantId+}++impl DatabaseBackedConfig for UnverifiedWebhookRateLimitEnabled {+ const KEY: &'static str = "unverified_webhook_rate_limit_enabled";++ fn db_key(_dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ // Unverified webhook rate limiting is configured only in superposition, so there is no db fallback.+ None+ }+}++config! {+ superposition_key = UNVERIFIED_WEBHOOK_RATE_LIMIT_WINDOW_IN_SECS,+ output = u32,+ default = 60u32,+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantId,+ targeting_key = id_type::MerchantId+}++impl DatabaseBackedConfig for UnverifiedWebhookRateLimitWindowInSecs {+ const KEY: &'static str = "unverified_webhook_rate_limit_window_in_secs";++ fn db_key(_dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ None+ }+}++config! {+ superposition_key = UNVERIFIED_WEBHOOK_MERCHANT_RATE_LIMIT,+ output = u32,+ default = 60u32,+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantId,+ targeting_key = id_type::MerchantId+}++impl DatabaseBackedConfig for UnverifiedWebhookMerchantRateLimit {+ const KEY: &'static str = "unverified_webhook_merchant_rate_limit";++ fn db_key(_dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ None+ }+}++config! {+ superposition_key = UNVERIFIED_WEBHOOK_PROFILE_RATE_LIMIT,+ output = u32,+ default = 0u32,+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ targeting_key = id_type::ProfileId+}++impl DatabaseBackedConfig for UnverifiedWebhookProfileRateLimit {+ const KEY: &'static str = "unverified_webhook_profile_rate_limit";++ fn db_key(_dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ None+ }+}++config! {+ superposition_key = UNVERIFIED_WEBHOOK_MERCHANT_CONNECTOR_ACCOUNT_RATE_LIMIT,+ output = u32,+ default = 0u32,+ requires = dimension_state::DimensionsWithMerchantConnectorAccount,+ targeting_key = id_type::MerchantConnectorAccountId+}++impl DatabaseBackedConfig for UnverifiedWebhookMerchantConnectorAccountRateLimit {+ const KEY: &'static str = "unverified_webhook_merchant_connector_account_rate_limit";++ fn db_key(_dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ None+ }+}+config! {superposition_key = SAVE_WALLET_DECRYPTED_DATA,output = bool,diff --git a/crates/router/src/core/configs/dimension_state.rs b/crates/router/src/core/configs/dimension_state.rsindex bd37cf8de1..11db723f37 100644--- a/crates/router/src/core/configs/dimension_state.rs+++ b/crates/router/src/core/configs/dimension_state.rs@@ -796,3 +796,76 @@ pub type DimensionsWithProcessorMerchantIdAndPaymentMethodType = Dimensions<NoWebhookEvent,HasPaymentMethodType,>;++/// Dimensions for configs that can be targeted down to a single merchant connector account.+///+/// `merchant_connector_id` is not part of the generic [`Dimensions`] state, so this wraps a+/// profile-scoped dimension state and adds the connector and the merchant connector account to+/// the Superposition context.+#[derive(Clone)]+pub struct DimensionsWithMerchantConnectorAccount {+ dimensions: DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ connector: Option<Connector>,+ merchant_connector_id: id_type::MerchantConnectorAccountId,+}++impl DimensionsWithMerchantConnectorAccount {+ pub fn new(+ dimensions: DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ connector: Option<Connector>,+ merchant_connector_id: id_type::MerchantConnectorAccountId,+ ) -> Self {+ Self {+ dimensions,+ connector,+ merchant_connector_id,+ }+ }+}++impl DimensionsBase for DimensionsWithMerchantConnectorAccount {+ fn to_superposition_context(&self) -> Option<superposition::ConfigContext> {+ let mut ctx = self.dimensions.to_superposition_context()?;++ if let Some(connector) = self.connector {+ ctx = ctx.with("connector", connector.to_string().as_str());+ }++ Some(ctx.with(+ "merchant_connector_id",+ self.merchant_connector_id.get_string_repr(),+ ))+ }++ fn get_provider_merchant_id(&self) -> Option<&id_type::MerchantId> {+ self.dimensions.get_provider_merchant_id()+ }++ fn get_processor_merchant_id(&self) -> Option<&id_type::MerchantId> {+ self.dimensions.get_processor_merchant_id()+ }++ fn get_organization_id(&self) -> Option<&id_type::OrganizationId> {+ self.dimensions.get_organization_id()+ }++ fn get_profile_id(&self) -> Option<&id_type::ProfileId> {+ self.dimensions.get_profile_id()+ }++ fn get_connector(&self) -> Option<Connector> {+ self.connector+ }++ fn get_payout_retry_type(&self) -> Option<&PayoutRetryType> {+ self.dimensions.get_payout_retry_type()+ }++ fn get_incoming_webhook_event(&self) -> Option<IncomingWebhookEvent> {+ self.dimensions.get_incoming_webhook_event()+ }++ fn get_payment_method_type(&self) -> Option<PaymentMethodType> {+ self.dimensions.get_payment_method_type()+ }+}diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rsindex a08893e3fc..c2d9c2e55e 100644--- a/crates/router/src/core/metrics.rs+++ b/crates/router/src/core/metrics.rs@@ -44,6 +44,12 @@ counter_metric!(counter_metric!(WEBHOOK_INCOMING_COUNT, GLOBAL_METER);counter_metric!(WEBHOOK_INCOMING_FILTERED_COUNT, GLOBAL_METER);counter_metric!(WEBHOOK_SOURCE_VERIFIED_COUNT, GLOBAL_METER);+// No. of unverified incoming webhooks checked against the rate limits+counter_metric!(WEBHOOK_UNVERIFIED_RATE_LIMIT_CHECKED_COUNT, GLOBAL_METER);+// No. of unverified incoming webhooks rejected for exceeding a rate limit+counter_metric!(WEBHOOK_UNVERIFIED_RATE_LIMITED_COUNT, GLOBAL_METER);+// No. of unverified incoming webhooks let through because the rate limit check failed+counter_metric!(WEBHOOK_UNVERIFIED_RATE_LIMITER_ERROR_COUNT, GLOBAL_METER);counter_metric!(WEBHOOK_OUTGOING_COUNT, GLOBAL_METER);counter_metric!(WEBHOOK_OUTGOING_RECEIVED_COUNT, GLOBAL_METER);counter_metric!(WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT, GLOBAL_METER);diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rsindex 0705bf8616..8cbcdc24db 100644--- a/crates/router/src/core/webhooks.rs+++ b/crates/router/src/core/webhooks.rs@@ -13,6 +13,7 @@ mod outgoing_v2;#[cfg(all(feature = "revenue_recovery", feature = "v2"))]pub mod recovery_incoming;pub mod types;+pub mod unverified_rate_limit;pub mod utils;#[cfg(feature = "olap")]pub mod webhook_events;diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex 0941fdfe2d..cc847dbcf8 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -55,7 +55,7 @@ use crate::{types::UNIFIED_AUTHENTICATION_SERVICE, utils as uas_utils,},unified_connector_service, utils as core_utils,- webhooks::{network_tokenization_incoming, utils},+ webhooks::{network_tokenization_incoming, unverified_rate_limit, utils},},logger,routes::{app::ReqState, lock_utils, SessionState},@@ -539,6 +539,15 @@ async fn process_webhook_business_logic(// if webhook consumption is mandatory for connector, fail webhook// so that merchant can retrigger it after updating merchant_secretreturn Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into());+ } else {+ // Unverified webhooks fall back to syncing with the connector, so cap how many of them+ // each merchant, profile and merchant connector account can push through+ unverified_rate_limit::check_unverified_webhook_rate_limit(+ state,+ platform,+ &merchant_connector_account,+ )+ .await?;}logger::info!(source_verified=?source_verified);@@ -771,6 +780,15 @@ fn handle_incoming_webhook_error(WebhookResponseTracker,common_utils::pii::SecretSerdeValue,)> {+ // A rate limited webhook must reach the connector as a 429 so that it is retried later,+ // never as an acknowledgement+ if matches!(+ error.current_context(),+ errors::ApiErrorResponse::WebhookRateLimited+ ) {+ return Err(error);+ }+logger::error!(?error, "Incoming webhook flow failed");// fetch the connector enum from the connector namediff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rsindex ad4210ffd0..d0fb069bf6 100644--- a/crates/router/src/core/webhooks/incoming_v2.rs+++ b/crates/router/src/core/webhooks/incoming_v2.rs@@ -29,7 +29,8 @@ use crate::{transformers::{GenerateResponse, ToResponse},},webhooks::{- create_event_and_trigger_outgoing_webhook, utils::construct_webhook_router_data,+ create_event_and_trigger_outgoing_webhook, unverified_rate_limit,+ utils::construct_webhook_router_data,},},db::StorageInterface,@@ -301,6 +302,17 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>() {(true, false) => Err(errors::ApiErrorResponse::WebhookAuthenticationFailed)?,_ => {+ // Unverified webhooks fall back to syncing with the connector, so cap how many of+ // them each merchant, profile and merchant connector account can push through+ if !source_verified {+ unverified_rate_limit::check_unverified_webhook_rate_limit(+ &state,+ &platform,+ &merchant_connector_account,+ )+ .await?;+ }+event_object = connector.get_webhook_resource_object(&request_details).switch()diff --git a/crates/router/src/core/webhooks/unverified_rate_limit.rs b/crates/router/src/core/webhooks/unverified_rate_limit.rsnew file mode 100644index 0000000000..cd869208cb--- /dev/null+++ b/crates/router/src/core/webhooks/unverified_rate_limit.rs@@ -0,0 +1,308 @@+//! Rate limiting for incoming webhooks whose source verification failed.+//!+//! An unverified webhook falls back to syncing with the connector (payment sync, refund sync,+//! payout retrieve, relay sync), so each one can trigger a connector call made with the+//! merchant's credentials. This caps how many unverified webhooks each merchant, profile and+//! merchant connector account can push through per window. Verified webhooks are never counted.+//!+//! Enablement, the window and the limit for each level are read from Superposition, so they can be+//! overridden per merchant, profile, connector or merchant connector account.++use std::str::FromStr;++use common_enums::connector_enums::Connector;+use error_stack::{report, ResultExt};+use router_env::{logger, tracing::Instrument};++use super::MERCHANT_ID;+use crate::{+ core::{configs::dimension_state, errors, metrics},+ routes::SessionState,+ types::domain,+};++const WEBHOOK_RATE_LIMIT_KEY_PREFIX: &str = "webhook_rate_limit";++#[derive(Clone, Copy, Debug, strum::IntoStaticStr)]+#[strum(serialize_all = "snake_case")]+enum RateLimitLevel {+ Merchant,+ Profile,+ MerchantConnectorAccount,+}++struct RateLimitBucket {+ level: RateLimitLevel,+ key: String,+ limit: u32,+}++/// Counts an unverified webhook against the merchant, profile and merchant connector account+/// limits.+///+/// Returns `WebhookRateLimited` when enabled and one of the limits has been reached.+/// Any failure while checking the limits lets the webhook through.+pub async fn check_unverified_webhook_rate_limit(+ state: &SessionState,+ platform: &domain::Platform,+ merchant_connector_account: &domain::MerchantConnectorAccount,+) -> errors::RouterResult<()> {+ let merchant_id = platform.get_processor().get_account().get_id();+ let connector_name = merchant_connector_account.get_connector_name_as_string();++ // Each limit is resolved with only the dimensions of its own level, so an override set at a+ // narrower level can never change the limit of a bucket shared by a wider one+ let merchant_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());+ let profile_dimensions =+ merchant_dimensions.with_profile_id(merchant_connector_account.profile_id.clone());+ let merchant_connector_account_dimensions =+ dimension_state::DimensionsWithMerchantConnectorAccount::new(+ profile_dimensions.clone(),+ Connector::from_str(&connector_name)+ .inspect_err(|error| {+ logger::warn!(+ ?error,+ connector = %connector_name,+ "Failed to parse connector for unverified webhook rate limit dimensions"+ )+ })+ .ok(),+ merchant_connector_account.get_id(),+ );++ let enabled = merchant_connector_account_dimensions+ .get_unverified_webhook_rate_limit_enabled(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ Some(merchant_id),+ )+ .await;++ if enabled {+ let limits = RateLimitDimensions {+ merchant: merchant_dimensions,+ profile: profile_dimensions,+ merchant_connector_account: merchant_connector_account_dimensions,+ };+ count_against_limits(state, merchant_id, merchant_connector_account, &limits).await+ } else {+ Ok(())+ }+}++/// The dimensions each level's configs are resolved with.+struct RateLimitDimensions {+ merchant: dimension_state::DimensionsWithProcessorAndProviderMerchantId,+ profile: dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ merchant_connector_account: dimension_state::DimensionsWithMerchantConnectorAccount,+}++/// Resolves the window and limits, then counts the webhook against every level that has a limit.+async fn count_against_limits(+ state: &SessionState,+ merchant_id: &common_utils::id_type::MerchantId,+ merchant_connector_account: &domain::MerchantConnectorAccount,+ dimensions: &RateLimitDimensions,+) -> errors::RouterResult<()> {+ let connector_name = merchant_connector_account.get_connector_name_as_string();+ let merchant_connector_id = merchant_connector_account.get_id();+ let storage = state.store.as_ref();+ let superposition_client = state.superposition_service.as_ref();+ let targeting_key = Some(merchant_id);++ // The window is shared by all buckets of a merchant, so it is resolved at the merchant level+ let window_in_secs = dimensions+ .merchant+ .get_unverified_webhook_rate_limit_window_in_secs(+ storage,+ superposition_client,+ targeting_key,+ )+ .await;+ let merchant_limit = dimensions+ .merchant+ .get_unverified_webhook_merchant_rate_limit(storage, superposition_client, targeting_key)+ .await;+ let profile_limit = dimensions+ .profile+ .get_unverified_webhook_profile_rate_limit(+ storage,+ superposition_client,+ Some(&merchant_connector_account.profile_id),+ )+ .await;+ let merchant_connector_account_limit = dimensions+ .merchant_connector_account+ .get_unverified_webhook_merchant_connector_account_rate_limit(+ storage,+ superposition_client,+ Some(&merchant_connector_id),+ )+ .await;++ // A limit of 0 disables its level+ let buckets: Vec<RateLimitBucket> = [+ (+ RateLimitLevel::Merchant,+ format!(+ "{WEBHOOK_RATE_LIMIT_KEY_PREFIX}:merchant:{}",+ merchant_id.get_string_repr()+ ),+ merchant_limit,+ ),+ (+ RateLimitLevel::Profile,+ format!(+ "{WEBHOOK_RATE_LIMIT_KEY_PREFIX}:profile:{}",+ merchant_connector_account.profile_id.get_string_repr()+ ),+ profile_limit,+ ),+ (+ RateLimitLevel::MerchantConnectorAccount,+ format!(+ "{WEBHOOK_RATE_LIMIT_KEY_PREFIX}:mca:{}",+ merchant_connector_id.get_string_repr()+ ),+ merchant_connector_account_limit,+ ),+ ]+ .into_iter()+ .filter(|(_, _, limit)| *limit > 0)+ .map(|(level, key, limit)| RateLimitBucket { level, key, limit })+ .collect();++ if buckets.is_empty() || window_in_secs == 0 {+ Ok(())+ } else {+ metrics::WEBHOOK_UNVERIFIED_RATE_LIMIT_CHECKED_COUNT.add(+ 1,+ router_env::metric_attributes!(+ (MERCHANT_ID, merchant_id.clone()),+ ("connector", connector_name.clone())+ ),+ );++ match increment_and_check(state, &buckets, window_in_secs).await {+ Ok(None) => Ok(()),+ Ok(Some(level)) => {+ let level: &'static str = level.into();+ metrics::WEBHOOK_UNVERIFIED_RATE_LIMITED_COUNT.add(+ 1,+ router_env::metric_attributes!(+ (MERCHANT_ID, merchant_id.clone()),+ ("connector", connector_name),+ ("level", level)+ ),+ );+ logger::info!(+ rate_limit_level = level,+ profile_id = %merchant_connector_account.profile_id.get_string_repr(),+ merchant_connector_id = %merchant_connector_id.get_string_repr(),+ "Unverified webhook rate limit reached"+ );++ Err(report!(errors::ApiErrorResponse::WebhookRateLimited))+ }+ Err(error) => {+ logger::error!(+ ?error,+ "Failed to check unverified webhook rate limit, letting the webhook through"+ );+ metrics::WEBHOOK_UNVERIFIED_RATE_LIMITER_ERROR_COUNT.add(+ 1,+ router_env::metric_attributes!(+ (MERCHANT_ID, merchant_id.clone()),+ ("connector", connector_name)+ ),+ );++ Ok(())+ }+ }+ }+}++/// Counts the webhook in every bucket and returns the level of the first bucket that went over+/// its limit, if any.+///+/// Each bucket is incremented with its own command and the commands run concurrently, before any+/// limit is checked. `Ok(None)` means every bucket was still within its limit. `Ok(Some(level))` means the bucket of that level was+/// already full, in which case the webhook is rejected and a background task takes it back out+/// of every bucket, so that rejected webhooks do not use up the allowance.+///+/// Until that task has run, the counts are one too high. Another webhook checked in that moment+/// can be rejected although there was room for it, which only happens close to a limit.+///+/// The buckets are independent keys, so if incrementing one of them fails, the others can already+/// have been incremented. The webhook is then let through and stays counted in those buckets+/// until their window ends.+async fn increment_and_check(+ state: &SessionState,+ buckets: &[RateLimitBucket],+ window_in_secs: u32,+) -> errors::RouterResult<Option<RateLimitLevel>> {+ let redis_conn = state+ .store+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get redis connection")?;++ let keys = buckets+ .iter()+ .map(|bucket| redis_interface::RedisKey::from(&bucket.key))+ .collect::<Vec<_>>();+ let window_in_secs = i64::from(window_in_secs);++ // A bucket is created with the window as its expiry when the first webhook of a window is+ // counted, and later webhooks leave that expiry untouched, which makes the window fixed+ let counts = futures::future::try_join_all(+ keys.iter()+ .map(|key| redis_conn.increment_key_with_expiry(key, window_in_secs)),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to increment the unverified webhook rate limit buckets")?;++ // `try_join_all` returns the counts in the order of `keys`, which is the order of `buckets`,+ // regardless of which future finishes first. The count includes this webhook, so a bucket is over+ // its limit only when the count is greater than the limit+ let exceeded_level = buckets+ .iter()+ .zip(counts)+ .find(|(bucket, count)| *count > i64::from(bucket.limit))+ .map(|(bucket, _)| bucket.level);++ // A rejected webhook was already counted in every bucket by the increment above. Take it+ // back out with a decrement, so that rejected webhooks do not use up the allowance.+ // This runs in the background because the response does not need to wait for it+ if exceeded_level.is_some() {+ tokio::spawn(+ async move {+ // `join_all` attempts every decrement, so a failure for one bucket does not stop+ // the other buckets from being decremented+ futures::future::join_all(+ keys.iter()+ .map(|key| redis_conn.decrement_key_with_expiry(key, window_in_secs)),+ )+ .await+ .into_iter()+ .for_each(|result| {+ result+ .inspect_err(|error| {+ logger::error!(+ ?error,+ "Failed to decrement an unverified webhook rate limit bucket"+ )+ })+ .ok();+ });+ }+ .in_current_span(),+ );+ }++ Ok(exceeded_level)+}