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): add webhook source verification support for multiple mca of the same connector (#1897)
Sai Harsha Vardhan3554fec1c1ab
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rsindex 021cc82402..874e21ce9c 100644--- a/crates/api_models/src/webhooks.rs+++ b/crates/api_models/src/webhooks.rs@@ -67,11 +67,13 @@ impl From<IncomingWebhookEvent> for WebhookFlow {pub type MerchantWebhookConfig = std::collections::HashSet<IncomingWebhookEvent>;+#[derive(Clone)]pub enum RefundIdType {RefundId(String),ConnectorRefundId(String),}+#[derive(Clone)]pub enum ObjectReferenceId {PaymentId(payments::PaymentIdType),RefundId(RefundIdType),diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rsindex 54cf4b35ca..df47395f21 100644--- a/crates/router/src/connector/adyen.rs+++ b/crates/router/src/connector/adyen.rs@@ -1382,9 +1382,10 @@ impl api::IncomingWebhook for Adyen {&self,db: &dyn StorageInterface,request: &api::IncomingWebhookRequestDetails<'_>,- merchant_id: &str,+ merchant_account: &domain::MerchantAccount,connector_label: &str,key_store: &domain::MerchantKeyStore,+ object_reference_id: api_models::webhooks::ObjectReferenceId,) -> CustomResult<bool, errors::ConnectorError> {let signature = self.get_webhook_source_verification_signature(request)@@ -1392,14 +1393,19 @@ impl api::IncomingWebhook for Adyen {let secret = self.get_webhook_source_verification_merchant_secret(db,- merchant_id,+ merchant_account,connector_label,key_store,+ object_reference_id,).await.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;let message = self- .get_webhook_source_verification_message(request, merchant_id, &secret)+ .get_webhook_source_verification_message(+ request,+ &merchant_account.merchant_id,+ &secret,+ ).change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;let raw_key = hex::decode(secret)diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rsindex dd73a649eb..1dddead0f5 100644--- a/crates/router/src/connector/bluesnap.rs+++ b/crates/router/src/connector/bluesnap.rs@@ -994,9 +994,10 @@ impl api::IncomingWebhook for Bluesnap {&self,db: &dyn StorageInterface,request: &api::IncomingWebhookRequestDetails<'_>,- merchant_id: &str,+ merchant_account: &domain::MerchantAccount,connector_label: &str,key_store: &domain::MerchantKeyStore,+ object_reference_id: api_models::webhooks::ObjectReferenceId,) -> CustomResult<bool, errors::ConnectorError> {let algorithm = self.get_webhook_source_verification_algorithm(request)@@ -1008,14 +1009,19 @@ impl api::IncomingWebhook for Bluesnap {let mut secret = self.get_webhook_source_verification_merchant_secret(db,- merchant_id,+ merchant_account,connector_label,key_store,+ object_reference_id,).await.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;let mut message = self- .get_webhook_source_verification_message(request, merchant_id, &secret)+ .get_webhook_source_verification_message(+ request,+ &merchant_account.merchant_id,+ &secret,+ ).change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;message.append(&mut secret);algorithmdiff --git a/crates/router/src/connector/cashtocode.rs b/crates/router/src/connector/cashtocode.rsindex 0e322fdec6..f1dc49966d 100644--- a/crates/router/src/connector/cashtocode.rs+++ b/crates/router/src/connector/cashtocode.rs@@ -322,9 +322,10 @@ impl api::IncomingWebhook for Cashtocode {&self,db: &dyn StorageInterface,request: &api::IncomingWebhookRequestDetails<'_>,- merchant_id: &str,+ merchant_account: &domain::MerchantAccount,connector_label: &str,key_store: &domain::MerchantKeyStore,+ object_reference_id: api_models::webhooks::ObjectReferenceId,) -> CustomResult<bool, errors::ConnectorError> {let signature = self.get_webhook_source_verification_signature(request)@@ -332,9 +333,10 @@ impl api::IncomingWebhook for Cashtocode {let secret = self.get_webhook_source_verification_merchant_secret(db,- merchant_id,+ merchant_account,connector_label,key_store,+ object_reference_id,).await.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rsindex 960b3bbfc9..29993a015e 100644--- a/crates/router/src/connector/rapyd.rs+++ b/crates/router/src/connector/rapyd.rs@@ -746,9 +746,10 @@ impl api::IncomingWebhook for Rapyd {&self,db: &dyn StorageInterface,request: &api::IncomingWebhookRequestDetails<'_>,- merchant_id: &str,+ merchant_account: &domain::MerchantAccount,connector_label: &str,key_store: &domain::MerchantKeyStore,+ object_reference_id: api_models::webhooks::ObjectReferenceId,) -> CustomResult<bool, errors::ConnectorError> {let signature = self.get_webhook_source_verification_signature(request)@@ -756,14 +757,19 @@ impl api::IncomingWebhook for Rapyd {let secret = self.get_webhook_source_verification_merchant_secret(db,- merchant_id,+ merchant_account,connector_label,key_store,+ object_reference_id,).await.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;let message = self- .get_webhook_source_verification_message(request, merchant_id, &secret)+ .get_webhook_source_verification_message(+ request,+ &merchant_account.merchant_id,+ &secret,+ ).change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;let stringify_auth = String::from_utf8(secret.to_vec())diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rsindex 4f16c91413..a024923be6 100644--- a/crates/router/src/connector/stax.rs+++ b/crates/router/src/connector/stax.rs@@ -758,9 +758,10 @@ impl api::IncomingWebhook for Stax {&self,_db: &dyn StorageInterface,_request: &api::IncomingWebhookRequestDetails<'_>,- _merchant_id: &str,+ _merchant_account: &domain::MerchantAccount,_connector_label: &str,_key_store: &domain::MerchantKeyStore,+ _object_reference_id: api_models::webhooks::ObjectReferenceId,) -> CustomResult<bool, errors::ConnectorError> {Ok(false)}diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rsindex 3a201eb44b..2cce8cf838 100644--- a/crates/router/src/connector/zen.rs+++ b/crates/router/src/connector/zen.rs@@ -557,9 +557,10 @@ impl api::IncomingWebhook for Zen {&self,db: &dyn StorageInterface,request: &api::IncomingWebhookRequestDetails<'_>,- merchant_id: &str,+ merchant_account: &domain::MerchantAccount,connector_label: &str,key_store: &domain::MerchantKeyStore,+ object_reference_id: api_models::webhooks::ObjectReferenceId,) -> CustomResult<bool, errors::ConnectorError> {let algorithm = self.get_webhook_source_verification_algorithm(request)?;@@ -567,13 +568,17 @@ impl api::IncomingWebhook for Zen {let mut secret = self.get_webhook_source_verification_merchant_secret(db,- merchant_id,+ merchant_account,connector_label,key_store,+ object_reference_id,).await?;- let mut message =- self.get_webhook_source_verification_message(request, merchant_id, &secret)?;+ let mut message = self.get_webhook_source_verification_message(+ request,+ &merchant_account.merchant_id,+ &secret,+ )?;message.append(&mut secret);algorithm.verify_signature(&secret, &signature, &message)diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rsindex 4c554b2bbb..b205da1eca 100644--- a/crates/router/src/core/webhooks.rs+++ b/crates/router/src/core/webhooks.rs@@ -751,13 +751,19 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>(let flow_type: api::WebhookFlow = event_type.to_owned().into();if process_webhook_further && !matches!(flow_type, api::WebhookFlow::ReturnResponse) {+ let object_ref_id = connector+ .get_webhook_object_reference_id(&request_details)+ .switch()+ .attach_printable("Could not find object reference id in incoming webhook body")?;+let source_verified = connector.verify_webhook_source(&*state.store,&request_details,- &merchant_account.merchant_id,+ &merchant_account,connector_name,&key_store,+ object_ref_id.clone(),).await.switch()@@ -775,10 +781,6 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType>(}logger::info!(source_verified=?source_verified);- let object_ref_id = connector- .get_webhook_object_reference_id(&request_details)- .switch()- .attach_printable("Could not find object reference id in incoming webhook body")?;let event_object = connector.get_webhook_resource_object(&request_details)diff --git a/crates/router/src/types/api/webhooks.rs b/crates/router/src/types/api/webhooks.rsindex a2d82d412c..a792d984e9 100644--- a/crates/router/src/types/api/webhooks.rs+++ b/crates/router/src/types/api/webhooks.rs@@ -13,7 +13,7 @@ use crate::{db::StorageInterface,logger, services,types::domain,- utils::crypto,+ utils::{self, crypto},};pub struct IncomingWebhookRequestDetails<'a> {@@ -78,19 +78,30 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {async fn get_webhook_source_verification_merchant_secret(&self,db: &dyn StorageInterface,- merchant_id: &str,+ merchant_account: &domain::MerchantAccount,connector_name: &str,key_store: &domain::MerchantKeyStore,+ object_reference_id: ObjectReferenceId,) -> CustomResult<Vec<u8>, errors::ConnectorError> {+ let merchant_id = merchant_account.merchant_id.as_str();let debug_suffix = format!("For merchant_id: {}, and connector_name: {}",merchant_id, connector_name);let default_secret = "default_secret".to_string();+ let connector_label = utils::get_connector_label_using_object_reference_id(+ db,+ object_reference_id,+ merchant_account,+ connector_name,+ )+ .await+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)+ .attach_printable("Error while fetching connector_label")?;let merchant_connector_account_result = db- .find_merchant_connector_account_by_merchant_id_connector_name(+ .find_merchant_connector_account_by_merchant_id_connector_label(merchant_id,- connector_name,+ &connector_label,key_store,).await;@@ -149,9 +160,10 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {&self,db: &dyn StorageInterface,request: &IncomingWebhookRequestDetails<'_>,- merchant_id: &str,+ merchant_account: &domain::MerchantAccount,connector_label: &str,key_store: &domain::MerchantKeyStore,+ object_reference_id: ObjectReferenceId,) -> CustomResult<bool, errors::ConnectorError> {let algorithm = self.get_webhook_source_verification_algorithm(request)@@ -163,14 +175,19 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {let secret = self.get_webhook_source_verification_merchant_secret(db,- merchant_id,+ merchant_account,connector_label,key_store,+ object_reference_id,).await.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;let message = self- .get_webhook_source_verification_message(request, merchant_id, &secret)+ .get_webhook_source_verification_message(+ request,+ &merchant_account.merchant_id,+ &secret,+ ).change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;algorithm.verify_signature(&secret, &signature, &message)diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex 1c9d6f4300..79ff18296d 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -5,6 +5,7 @@ pub mod ext_traits;#[cfg(feature = "kv_store")]pub mod storage_partitioning;+use api_models::{payments, webhooks};use base64::Engine;pub use common_utils::{crypto,@@ -23,10 +24,11 @@ use uuid::Uuid;pub use self::ext_traits::{OptionExt, ValidateCall};use crate::{consts,- core::errors::{self, CustomResult, RouterResult},+ core::errors::{self, CustomResult, RouterResult, StorageErrorExt},+ db::StorageInterface,logger,routes::metrics,- types,+ types::{self, domain, storage},};pub mod error_parser {@@ -180,6 +182,157 @@ mod tests {}}+pub async fn find_payment_intent_from_payment_id_type(+ db: &dyn StorageInterface,+ payment_id_type: payments::PaymentIdType,+ merchant_account: &domain::MerchantAccount,+) -> CustomResult<storage::PaymentIntent, errors::ApiErrorResponse> {+ match payment_id_type {+ payments::PaymentIdType::PaymentIntentId(payment_id) => db+ .find_payment_intent_by_payment_id_merchant_id(+ &payment_id,+ &merchant_account.merchant_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound),+ payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id) => {+ let attempt = db+ .find_payment_attempt_by_merchant_id_connector_txn_id(+ &merchant_account.merchant_id,+ &connector_transaction_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ db.find_payment_intent_by_payment_id_merchant_id(+ &attempt.payment_id,+ &merchant_account.merchant_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ }+ payments::PaymentIdType::PaymentAttemptId(attempt_id) => {+ let attempt = db+ .find_payment_attempt_by_attempt_id_merchant_id(+ &attempt_id,+ &merchant_account.merchant_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ db.find_payment_intent_by_payment_id_merchant_id(+ &attempt.payment_id,+ &merchant_account.merchant_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ }+ payments::PaymentIdType::PreprocessingId(_) => {+ Err(errors::ApiErrorResponse::PaymentNotFound)?+ }+ }+}++pub async fn find_payment_intent_from_refund_id_type(+ db: &dyn StorageInterface,+ refund_id_type: webhooks::RefundIdType,+ merchant_account: &domain::MerchantAccount,+ connector_name: &str,+) -> CustomResult<storage::PaymentIntent, errors::ApiErrorResponse> {+ let refund = match refund_id_type {+ webhooks::RefundIdType::RefundId(id) => db+ .find_refund_by_merchant_id_refund_id(+ &merchant_account.merchant_id,+ &id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?,+ webhooks::RefundIdType::ConnectorRefundId(id) => db+ .find_refund_by_merchant_id_connector_refund_id_connector(+ &merchant_account.merchant_id,+ &id,+ connector_name,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?,+ };+ let attempt = db+ .find_payment_attempt_by_attempt_id_merchant_id(+ &refund.attempt_id,+ &merchant_account.merchant_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ db.find_payment_intent_by_payment_id_merchant_id(+ &attempt.payment_id,+ &merchant_account.merchant_id,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+}++pub async fn get_connector_label_using_object_reference_id(+ db: &dyn StorageInterface,+ object_reference_id: webhooks::ObjectReferenceId,+ merchant_account: &domain::MerchantAccount,+ connector_name: &str,+) -> CustomResult<String, errors::ApiErrorResponse> {+ let mut primary_business_details = merchant_account+ .primary_business_details+ .clone()+ .parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to parse primary business details")?;+ //check if there is only one primary business details and get those details+ let (option_business_country, option_business_label) = match primary_business_details.pop() {+ Some(business_details) => {+ if primary_business_details.is_empty() {+ (+ Some(business_details.country),+ Some(business_details.business),+ )+ } else {+ (None, None)+ }+ }+ None => (None, None),+ };+ match (option_business_country, option_business_label) {+ (Some(business_country), Some(business_label)) => Ok(format!(+ "{connector_name}_{}_{}",+ business_country, business_label+ )),+ _ => {+ let payment_intent = match object_reference_id {+ webhooks::ObjectReferenceId::PaymentId(payment_id_type) => {+ find_payment_intent_from_payment_id_type(db, payment_id_type, merchant_account)+ .await?+ }+ webhooks::ObjectReferenceId::RefundId(refund_id_type) => {+ find_payment_intent_from_refund_id_type(+ db,+ refund_id_type,+ merchant_account,+ connector_name,+ )+ .await?+ }+ };+ Ok(format!(+ "{connector_name}_{}_{}",+ payment_intent.business_country, payment_intent.business_label+ ))+ }+ }+}+// validate json format for the errorpub fn handle_json_response_deserialization_failure(res: types::Response,