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

fix(core): Prevent Partial Registrations for Any Scope Identifier for Connector Webhook Register API (#13484)

Sayak Bhattacharyaf5ac09d89906
diff --git a/crates/api_models/src/merchant_connector_webhook_management.rs b/crates/api_models/src/merchant_connector_webhook_management.rs
index 4656e6faf6..b279193459 100644
--- a/crates/api_models/src/merchant_connector_webhook_management.rs
+++ b/crates/api_models/src/merchant_connector_webhook_management.rs
@@ -28,7 +28,7 @@ pub enum ScopeType {
EventType,
}
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)]
#[serde(into = "String", try_from = "String")]
pub enum ScopeIdentifier {
NotSpecific,
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index d05a8676b1..f98dacc4d6 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -7640,7 +7640,7 @@ type="Text"
label="Webhook Registration & Workspace Creation"
webhook_auto_configuration_supported=true
scope_type="payment_method_type"
-payment_method_types=["pix_emv", "pix_automatico_push", "pix_automatico_qr", "boleto"]
+payment_method_types=["pix_qr", "pix_automatico_push", "pix_automatico_qr", "boleto"]
[blackhawknetwork]
[[blackhawknetwork.gift_card]]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 151cb465ee..2b014c12a6 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -6655,7 +6655,7 @@ type="Text"
label="Webhook Registration & Workspace Creation"
webhook_auto_configuration_supported=true
scope_type="payment_method_type"
-payment_method_types=["pix_emv", "pix_automatico_push", "pix_automatico_qr", "boleto"]
+payment_method_types=["pix_qr", "pix_automatico_push", "pix_automatico_qr", "boleto"]
[blackhawknetwork]
[[blackhawknetwork.gift_card]]
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index c504c39c2c..0cf122e2b5 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -7616,7 +7616,7 @@ type="Text"
label="Webhook Registration & Workspace Creation"
webhook_auto_configuration_supported=true
scope_type="payment_method_type"
-payment_method_types=["pix_emv", "pix_automatico_push", "pix_automatico_qr", "boleto"]
+payment_method_types=["pix_qr", "pix_automatico_push", "pix_automatico_qr", "boleto"]
[blackhawknetwork]
[[blackhawknetwork.gift_card]]
diff --git a/crates/router/src/core/merchant_connector_webhook_management.rs b/crates/router/src/core/merchant_connector_webhook_management.rs
index 2d69f22572..d8fee7c2c5 100644
--- a/crates/router/src/core/merchant_connector_webhook_management.rs
+++ b/crates/router/src/core/merchant_connector_webhook_management.rs
@@ -1,4 +1,6 @@
mod transformers;
+use std::collections::{HashMap, HashSet};
+
use api_models::merchant_connector_webhook_management::{
ConnectorWebhookRegisterRequest as ApiConnectorWebhookRegisterRequest, ScopeIdentifier,
WebhookRegistrationResult,
@@ -231,6 +233,14 @@ pub async fn register_connector_webhook(
Option<common_utils::pii::SecretSerdeValue>,
Option<String>,
);
+ type GroupedRegistrationOutcomes = HashMap<
+ ScopeIdentifier,
+ Vec<(
+ WebhookRegistrationResult,
+ Option<common_utils::pii::SecretSerdeValue>,
+ Option<String>,
+ )>,
+ >;
let registration_futures = registration_plan.into_iter().map(|(identifier, base_url)| {
let state = &state;
@@ -384,25 +394,64 @@ pub async fn register_connector_webhook(
.into_iter()
.collect::<errors::RouterResult<Vec<RegistrationOutcome>>>()?;
let mut results = Vec::with_capacity(registration_outcomes.len());
- let mut registration_entries = Vec::new();
- let mut metadata_patches = Vec::new();
- let mut first_successful_webhook_id = None;
+ let mut grouped_outcomes: GroupedRegistrationOutcomes = HashMap::new();
for (identifier, result, metadata, connector_webhook_id) in registration_outcomes {
- if let Some(metadata) = metadata {
- metadata_patches.push(metadata);
- }
+ results.push(result.clone());
+ grouped_outcomes.entry(identifier).or_default().push((
+ result,
+ metadata,
+ connector_webhook_id,
+ ));
+ }
- if let Some(webhook_id) = connector_webhook_id {
- if first_successful_webhook_id.is_none() {
- first_successful_webhook_id = Some(webhook_id.clone());
+ // An identifier is considered fully registered only when every planned
+ // registration call for that identifier succeeds. Partially-failed
+ // identifiers are not persisted (and any existing entries for them are
+ // removed) so that the list API does not surface an incomplete scope.
+ let mut registration_entries = Vec::new();
+ let mut metadata_patches = Vec::new();
+ let mut first_successful_webhook_id = None;
+ let mut successful_identifiers = HashSet::new();
+ let mut scopes_to_remove = Vec::new();
+
+ for identifier in &requested {
+ let all_succeeded = grouped_outcomes
+ .get(identifier)
+ .map(|outcomes| {
+ outcomes.iter().all(|(result, _, webhook_id)| {
+ matches!(
+ result.status,
+ common_enums::WebhookRegistrationStatus::Success
+ ) && webhook_id.is_some()
+ })
+ })
+ .unwrap_or(false);
+
+ if all_succeeded {
+ successful_identifiers.insert(identifier.clone());
+ if let Some(outcomes) = grouped_outcomes.get(identifier) {
+ for (_, metadata, connector_webhook_id) in outcomes {
+ if let Some(webhook_id) = connector_webhook_id {
+ if first_successful_webhook_id.is_none() {
+ first_successful_webhook_id = Some(webhook_id.clone());
+ }
+ registration_entries.push((webhook_id.clone(), identifier.clone()));
+ }
+ if let Some(metadata) = metadata {
+ metadata_patches.push(metadata.clone());
+ }
+ }
}
- registration_entries.push((webhook_id, identifier));
+ } else {
+ scopes_to_remove.push(identifier.clone());
}
-
- results.push(result);
}
+ // Fully successful re-registrations should also replace any stale entries
+ // for the same scope so the list API does not show duplicate/outdated IDs.
+ scopes_to_remove.extend(successful_identifiers.iter().cloned());
+
// Run the GenerateSecret flow only when the connector requires it (e.g. Adyen) AND the
// register step returned a connector_webhook_id to operate on. A failure here does not
// fail registration — register success is still surfaced and the secret-generation error
@@ -431,6 +480,7 @@ pub async fn register_connector_webhook(
registration_entries,
generated_secret,
metadata_patches,
+ &scopes_to_remove,
)?;
let should_update_db = matches!(
diff --git a/crates/router/src/core/merchant_connector_webhook_management/transformers.rs b/crates/router/src/core/merchant_connector_webhook_management/transformers.rs
index cea8564685..4e225684b3 100644
--- a/crates/router/src/core/merchant_connector_webhook_management/transformers.rs
+++ b/crates/router/src/core/merchant_connector_webhook_management/transformers.rs
@@ -218,6 +218,8 @@ pub async fn construct_generate_secret_router_data<'a>(
})
}
+/// Recursively merges `patch` into `base`.
+/// Nested objects are merged key-by-key; non-object values are overwritten.
fn deep_merge_json_values(base: &mut serde_json::Value, patch: serde_json::Value) {
match (base, patch) {
(serde_json::Value::Object(base_map), serde_json::Value::Object(patch_map)) => {
@@ -234,16 +236,45 @@ fn deep_merge_json_values(base: &mut serde_json::Value, patch: serde_json::Value
}
}
+/// Checks whether a stored scope matches the given scope identifier.
+fn scope_matches_identifier(identifier: &ScopeIdentifier, scope: &ConnectorWebhookScope) -> bool {
+ match (identifier, scope) {
+ (ScopeIdentifier::NotSpecific, ConnectorWebhookScope::NotSpecific) => true,
+ (
+ ScopeIdentifier::PaymentMethodType(pmt),
+ ConnectorWebhookScope::PaymentMethodType { value },
+ ) => pmt == value,
+ (ScopeIdentifier::EventType(evt), ConnectorWebhookScope::EventType { value }) => {
+ evt == value
+ }
+ _ => false,
+ }
+}
+
#[cfg(feature = "v1")]
+/// Builds the DB update for connector webhook registration.
+///
+/// - `registration_entries`: `(connector_webhook_id, scope)` pairs that fully succeeded
+/// and must be persisted.
+/// - `scopes_to_remove`: scopes whose existing stored entries must be removed before
+/// inserting the new ones. This covers partially-failed scopes (so they are not
+/// persisted) and scopes that are being re-registered (so stale webhook IDs are
+/// replaced rather than duplicated).
pub fn construct_connector_webhook_registration_details(
merchant_connector_account: &domain::MerchantConnectorAccount,
registration_entries: Vec<(String, ScopeIdentifier)>,
generated_secret: Option<Secret<String>>,
metadata_patches: Vec<common_utils::pii::SecretSerdeValue>,
+ scopes_to_remove: &[ScopeIdentifier],
) -> RouterResult<domain::MerchantConnectorAccountUpdate> {
- let connector_webhook_registration_details = if registration_entries.is_empty() {
+ // Only touch stored registration details if we have something to add or remove.
+ let has_registration_changes = !registration_entries.is_empty() || !scopes_to_remove.is_empty();
+ let performed_removals = !scopes_to_remove.is_empty();
+
+ let connector_webhook_registration_details = if !has_registration_changes {
None
} else {
+ // Start from existing registrations, or an empty object if none exist.
let mut connector_webhook_registration_details = merchant_connector_account
.get_connector_webhook_registration_details()
.unwrap_or_else(|| serde_json::Value::Object(Default::default()));
@@ -252,6 +283,24 @@ pub fn construct_connector_webhook_registration_details(
.as_object_mut()
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
+ // Step 1: Remove stored entries for scopes that failed or are being replaced.
+ // Legacy (event_type based) and unparseable entries are kept unchanged.
+ if performed_removals {
+ let scopes_to_remove = scopes_to_remove.to_vec();
+ map.retain(|_, entry_value| {
+ let stored: Result<StoredConnectorWebhookEntry, _> =
+ serde_json::from_value(entry_value.clone());
+ match stored {
+ Ok(StoredConnectorWebhookEntry::New(scope)) => !scopes_to_remove
+ .iter()
+ .any(|identifier| scope_matches_identifier(identifier, &scope)),
+ Ok(StoredConnectorWebhookEntry::Legacy(_)) => true,
+ Err(_) => true,
+ }
+ });
+ }
+
+ // Step 2: Persist the new webhook IDs for fully-successful scopes.
for (connector_webhook_id, scope) in registration_entries {
let entry_value = match &scope {
ScopeIdentifier::NotSpecific => {
@@ -269,9 +318,18 @@ pub fn construct_connector_webhook_registration_details(
map.insert(connector_webhook_id, entry_value);
}
- Some(connector_webhook_registration_details)
+ if map.is_empty() {
+ // If we intentionally removed every entry, return an empty object so the
+ // DB update is still written. Returning None here would skip the update
+ // and leave stale registrations behind.
+ performed_removals.then(|| serde_json::Value::Object(Default::default()))
+ } else {
+ Some(connector_webhook_registration_details)
+ }
};
+ // Merge connector-returned metadata patches into the existing metadata,
+ // creating a fresh metadata object if none exists yet.
let metadata = if metadata_patches.is_empty() {
None
} else {
@@ -287,6 +345,8 @@ pub fn construct_connector_webhook_registration_details(
Some(common_utils::pii::SecretSerdeValue::new(merged_metadata))
};
+ // If the connector requires a generated webhook secret, persist it while preserving
+ // any existing additional_secret already stored for this merchant connector.
let connector_webhook_details = generated_secret
.map(|secret| {
build_connector_webhook_details_with_secret(merchant_connector_account, secret)
@@ -303,6 +363,8 @@ pub fn construct_connector_webhook_registration_details(
}
#[cfg(feature = "v1")]
+/// Encodes the generated webhook secret into `MerchantConnectorWebhookDetails`,
+/// preserving any existing `additional_secret` instead of overwriting it.
fn build_connector_webhook_details_with_secret(
merchant_connector_account: &domain::MerchantConnectorAccount,
secret: Secret<String>,
@@ -404,6 +466,10 @@ pub fn extract_requested_identifiers(scope: &Scope) -> Vec<ScopeIdentifier> {
#[cfg(feature = "v1")]
#[allow(deprecated)]
+/// Builds the response for the connector webhook register API.
+///
+/// Legacy requests receive a flattened single-status response. Non-legacy requests
+/// receive the full list of requested scope identifiers and one result per connector call.
pub fn construct_connector_webhook_registration_response(
results: Vec<WebhookRegistrationResult>,
scope_type: ScopeType,
@@ -411,6 +477,7 @@ pub fn construct_connector_webhook_registration_response(
generate_secret_response: Option<&ConnectorWebhookGenerateSecretResponse>,
is_legacy_request: bool,
) -> RouterResult<RegisterConnectorWebhookResponse> {
+ // Extract the optional webhook-secret generation status/error to include in the response.
let (secret_generation_status, secret_error) = generate_secret_response
.map(|resp| {
let secret_error =
@@ -424,6 +491,8 @@ pub fn construct_connector_webhook_registration_response(
})
.unwrap_or((None, None));
+ // Legacy callers only see one top-level status/id/error.
+ // Non-legacy callers receive the detailed per-call results below.
let (connector_webhook_id, webhook_registration_status, error_code, error_message) =
if is_legacy_request {
if let Some(success) = results
@@ -508,6 +577,10 @@ enum StoredConnectorWebhookEntry {
#[cfg(feature = "v1")]
#[allow(deprecated)]
+/// Converts the persisted `connector_webhook_registration_details` blob into a list response.
+///
+/// Supports both the old event_type-based entries and the new scope-based entries so that
+/// webhooks registered before this change continue to be listed correctly.
pub fn get_connector_webhook_list_response(
register_webhook_response: &Option<serde_json::Value>,
) -> RouterResult<Vec<ConnectorWebhookResponse>> {