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
refactor(webhook_events): allow listing unique webhook events based on profile ID (#5598)
Sanchith Hegde8bcda2cea480
diff --git a/api-reference/api-reference/event/events--delivery-attempt-list.mdx b/api-reference/api-reference/event/events--delivery-attempt-list.mdxindex 04cad3e5e1..52ed085f9d 100644--- a/api-reference/api-reference/event/events--delivery-attempt-list.mdx+++ b/api-reference/api-reference/event/events--delivery-attempt-list.mdx@@ -1,3 +1,3 @@----openapi: get /events/{merchant_id_or_profile_id}/{event_id}/attempts+openapi: get /events/{merchant_id}/{event_id}/attempts---\ No newline at end of filediff --git a/api-reference/api-reference/event/events--list.mdx b/api-reference/api-reference/event/events--list.mdxindex 580b705052..0b02af87e6 100644--- a/api-reference/api-reference/event/events--list.mdx+++ b/api-reference/api-reference/event/events--list.mdx@@ -1,3 +1,3 @@----openapi: get /events/{merchant_id_or_profile_id}+openapi: get /events/{merchant_id}---\ No newline at end of filediff --git a/api-reference/api-reference/event/events--manual-retry.mdx b/api-reference/api-reference/event/events--manual-retry.mdxindex 2bc2fce304..d52cb414bb 100644--- a/api-reference/api-reference/event/events--manual-retry.mdx+++ b/api-reference/api-reference/event/events--manual-retry.mdx@@ -1,3 +1,3 @@----openapi: post /events/{merchant_id_or_profile_id}/{event_id}/retry+openapi: post /events/{merchant_id}/{event_id}/retry---\ No newline at end of filediff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.jsonindex e163435956..b2383e2cb8 100644--- a/api-reference/openapi_spec.json+++ b/api-reference/openapi_spec.json@@ -4658,7 +4658,7 @@]}},- "/events/{merchant_id_or_profile_id}": {+ "/events/{merchant_id}": {"get": {"tags": ["Event"@@ -4668,9 +4668,9 @@"operationId": "List all Events associated with a Merchant Account or Business Profile","parameters": [{- "name": "merchant_id_or_profile_id",+ "name": "merchant_id","in": "path",- "description": "The unique identifier for the Merchant Account or Business Profile",+ "description": "The unique identifier for the Merchant Account.","required": true,"schema": {"type": "string"@@ -4729,6 +4729,16 @@"type": "string","nullable": true}+ },+ {+ "name": "profile_id",+ "in": "query",+ "description": "Only include Events associated with the Business Profile identified by the specified Business Profile ID.",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true+ }}],"responses": {@@ -4753,7 +4763,7 @@]}},- "/events/{merchant_id_or_profile_id}/{event_id}/attempts": {+ "/events/{merchant_id}/{event_id}/attempts": {"get": {"tags": ["Event"@@ -4763,9 +4773,9 @@"operationId": "List all delivery attempts for an Event","parameters": [{- "name": "merchant_id_or_profile_id",+ "name": "merchant_id","in": "path",- "description": "The unique identifier for the Merchant Account or Business Profile",+ "description": "The unique identifier for the Merchant Account.","required": true,"schema": {"type": "string"@@ -4803,7 +4813,7 @@]}},- "/events/{merchant_id_or_profile_id}/{event_id}/retry": {+ "/events/{merchant_id}/{event_id}/retry": {"post": {"tags": ["Event"@@ -4813,9 +4823,9 @@"operationId": "Manually retry the delivery of an Event","parameters": [{- "name": "merchant_id_or_profile_id",+ "name": "merchant_id","in": "path",- "description": "The unique identifier for the Merchant Account or Business Profile",+ "description": "The unique identifier for the Merchant Account.","required": true,"schema": {"type": "string"diff --git a/crates/api_models/src/webhook_events.rs b/crates/api_models/src/webhook_events.rsindex 2dcc6d6432..fa61cc0f25 100644--- a/crates/api_models/src/webhook_events.rs+++ b/crates/api_models/src/webhook_events.rs@@ -24,6 +24,9 @@ pub struct EventListConstraints {/// Filter all events associated with the specified object identifier (Payment Intent ID,/// Refund ID, etc.)pub object_id: Option<String>,++ /// Filter all events associated with the specified business profile ID.+ pub profile_id: Option<String>,}#[derive(Debug)]@@ -97,11 +100,7 @@ pub struct EventRetrieveResponse {impl common_utils::events::ApiEventMetric for EventRetrieveResponse {fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {Some(common_utils::events::ApiEventsType::Events {- merchant_id_or_profile_id: self- .event_information- .merchant_id- .get_string_repr()- .to_owned(),+ merchant_id: self.event_information.merchant_id.clone(),})}}@@ -148,42 +147,42 @@ pub struct OutgoingWebhookResponseContent {#[derive(Debug, serde::Serialize)]pub struct EventListRequestInternal {- pub merchant_id_or_profile_id: String,+ pub merchant_id: common_utils::id_type::MerchantId,pub constraints: EventListConstraints,}impl common_utils::events::ApiEventMetric for EventListRequestInternal {fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {Some(common_utils::events::ApiEventsType::Events {- merchant_id_or_profile_id: self.merchant_id_or_profile_id.clone(),+ merchant_id: self.merchant_id.clone(),})}}#[derive(Debug, serde::Serialize)]pub struct WebhookDeliveryAttemptListRequestInternal {- pub merchant_id_or_profile_id: String,+ pub merchant_id: common_utils::id_type::MerchantId,pub initial_attempt_id: String,}impl common_utils::events::ApiEventMetric for WebhookDeliveryAttemptListRequestInternal {fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {Some(common_utils::events::ApiEventsType::Events {- merchant_id_or_profile_id: self.merchant_id_or_profile_id.clone(),+ merchant_id: self.merchant_id.clone(),})}}#[derive(Debug, serde::Serialize)]pub struct WebhookDeliveryRetryRequestInternal {- pub merchant_id_or_profile_id: String,+ pub merchant_id: common_utils::id_type::MerchantId,pub event_id: String,}impl common_utils::events::ApiEventMetric for WebhookDeliveryRetryRequestInternal {fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {Some(common_utils::events::ApiEventsType::Events {- merchant_id_or_profile_id: self.merchant_id_or_profile_id.clone(),+ merchant_id: self.merchant_id.clone(),})}}diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rsindex c2294f865a..ac4b9c42a4 100644--- a/crates/common_utils/src/events.rs+++ b/crates/common_utils/src/events.rs@@ -58,7 +58,7 @@ pub enum ApiEventsType {dispute_id: String,},Events {- merchant_id_or_profile_id: String,+ merchant_id: id_type::MerchantId,},PaymentMethodCollectLink {link_id: String,diff --git a/crates/diesel_models/src/query/business_profile.rs b/crates/diesel_models/src/query/business_profile.rsindex 09fa700dae..fb80449cdc 100644--- a/crates/diesel_models/src/query/business_profile.rs+++ b/crates/diesel_models/src/query/business_profile.rs@@ -48,6 +48,20 @@ impl BusinessProfile {.await}+ pub async fn find_by_merchant_id_profile_id(+ conn: &PgPooledConn,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::profile_id.eq(profile_id.to_owned())),+ )+ .await+ }+pub async fn find_by_profile_name_merchant_id(conn: &PgPooledConn,profile_name: &str,diff --git a/crates/openapi/src/routes/webhook_events.rs b/crates/openapi/src/routes/webhook_events.rsindex fc06ffee58..c754f59e51 100644--- a/crates/openapi/src/routes/webhook_events.rs+++ b/crates/openapi/src/routes/webhook_events.rs@@ -3,12 +3,12 @@/// List all Events associated with a Merchant Account or Business Profile.#[utoipa::path(get,- path = "/events/{merchant_id_or_profile_id}",+ path = "/events/{merchant_id}",params((- "merchant_id_or_profile_id" = String,+ "merchant_id" = String,Path,- description = "The unique identifier for the Merchant Account or Business Profile"+ description = "The unique identifier for the Merchant Account."),("created_after" = Option<PrimitiveDateTime>,@@ -40,6 +40,11 @@description = "Only include Events associated with the specified object (Payment Intent ID, Refund ID, etc.). \Either only `object_id` must be specified, or one or more of `created_after`, `created_before`, `limit` and `offset` must be specified."),+ (+ "profile_id" = Option<String>,+ Query,+ description = "Only include Events associated with the Business Profile identified by the specified Business Profile ID."+ ),),responses((status = 200, description = "List of Events retrieved successfully", body = Vec<EventListItemResponse>),@@ -55,9 +60,9 @@ pub fn list_initial_webhook_delivery_attempts() {}/// List all delivery attempts for the specified Event.#[utoipa::path(get,- path = "/events/{merchant_id_or_profile_id}/{event_id}/attempts",+ path = "/events/{merchant_id}/{event_id}/attempts",params(- ("merchant_id_or_profile_id" = String, Path, description = "The unique identifier for the Merchant Account or Business Profile"),+ ("merchant_id" = String, Path, description = "The unique identifier for the Merchant Account."),("event_id" = String, Path, description = "The unique identifier for the Event"),),responses(@@ -74,9 +79,9 @@ pub fn list_webhook_delivery_attempts() {}/// Manually retry the delivery of the specified Event.#[utoipa::path(post,- path = "/events/{merchant_id_or_profile_id}/{event_id}/retry",+ path = "/events/{merchant_id}/{event_id}/retry",params(- ("merchant_id_or_profile_id" = String, Path, description = "The unique identifier for the Merchant Account or Business Profile"),+ ("merchant_id" = String, Path, description = "The unique identifier for the Merchant Account."),("event_id" = String, Path, description = "The unique identifier for the Event"),),responses(diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rsindex e7d0483a76..cf4a8d8726 100644--- a/crates/router/src/core/webhooks/webhook_events.rs+++ b/crates/router/src/core/webhooks/webhook_events.rs@@ -15,23 +15,23 @@ const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT: i64 = 100;#[derive(Debug)]enum MerchantAccountOrBusinessProfile {MerchantAccount(domain::MerchantAccount),- #[allow(dead_code)]BusinessProfile(domain::BusinessProfile),}#[instrument(skip(state))]pub async fn list_initial_delivery_attempts(state: SessionState,- merchant_id_or_profile_id: String,+ merchant_id: common_utils::id_type::MerchantId,constraints: api::webhook_events::EventListConstraints,) -> RouterResponse<Vec<api::webhook_events::EventListItemResponse>> {+ let profile_id = constraints.profile_id.clone();let constraints =api::webhook_events::EventListConstraintsInternal::foreign_try_from(constraints)?;let store = state.store.as_ref();let key_manager_state = &(&state).into();let (account, key_store) =- determine_identifier_and_get_key_store(state.clone(), merchant_id_or_profile_id).await?;+ get_account_and_key_store(state.clone(), merchant_id, profile_id).await?;let events = match constraints {api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter { object_id } => {@@ -110,38 +110,31 @@ pub async fn list_initial_delivery_attempts(#[instrument(skip(state))]pub async fn list_delivery_attempts(state: SessionState,- merchant_id_or_profile_id: String,+ merchant_id: common_utils::id_type::MerchantId,initial_attempt_id: String,) -> RouterResponse<Vec<api::webhook_events::EventRetrieveResponse>> {let store = state.store.as_ref();-- let (account, key_store) =- determine_identifier_and_get_key_store(state.clone(), merchant_id_or_profile_id).await?;let key_manager_state = &(&state).into();- let events = match account {- MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account) => {- store- .list_events_by_merchant_id_initial_attempt_id(- key_manager_state,- merchant_account.get_id(),- &initial_attempt_id,- &key_store,- )- .await- }- MerchantAccountOrBusinessProfile::BusinessProfile(business_profile) => {- store- .list_events_by_profile_id_initial_attempt_id(- key_manager_state,- &business_profile.profile_id,- &initial_attempt_id,- &key_store,- )- .await- }- }- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to list delivery attempts for initial event")?;++ let key_store = store+ .get_merchant_key_store_by_merchant_id(+ key_manager_state,+ &merchant_id,+ &store.get_master_key().to_vec().into(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;++ let events = store+ .list_events_by_merchant_id_initial_attempt_id(+ key_manager_state,+ &merchant_id,+ &initial_attempt_id,+ &key_store,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to list delivery attempts for initial event")?;if events.is_empty() {Err(error_stack::report!(@@ -161,13 +154,20 @@ pub async fn list_delivery_attempts(#[instrument(skip(state))]pub async fn retry_delivery_attempt(state: SessionState,- merchant_id_or_profile_id: String,+ merchant_id: common_utils::id_type::MerchantId,event_id: String,) -> RouterResponse<api::webhook_events::EventRetrieveResponse> {let store = state.store.as_ref();let key_manager_state = &(&state).into();- let (account, key_store) =- determine_identifier_and_get_key_store(state.clone(), merchant_id_or_profile_id).await?;++ let key_store = store+ .get_merchant_key_store_by_merchant_id(+ key_manager_state,+ &merchant_id,+ &store.get_master_key().to_vec().into(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;let event_to_retry = store.find_event_by_merchant_id_event_id(@@ -179,25 +179,16 @@ pub async fn retry_delivery_attempt(.await.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;- let business_profile = match account {- MerchantAccountOrBusinessProfile::MerchantAccount(_) => {- let business_profile_id = event_to_retry- .business_profile_id- .get_required_value("business_profile_id")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to read business profile ID from event to retry")?;- store- .find_business_profile_by_profile_id(- key_manager_state,- &key_store,- &business_profile_id,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to find business profile")- }- MerchantAccountOrBusinessProfile::BusinessProfile(business_profile) => Ok(business_profile),- }?;+ let business_profile_id = event_to_retry+ .business_profile_id+ .get_required_value("business_profile_id")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to read business profile ID from event to retry")?;+ let business_profile = store+ .find_business_profile_by_profile_id(key_manager_state, &key_store, &business_profile_id)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to find business profile")?;let delivery_attempt = storage::enums::WebhookDeliveryAttempt::ManualRetry;let new_event_id = super::utils::generate_event_id();@@ -271,77 +262,65 @@ pub async fn retry_delivery_attempt())}-async fn determine_identifier_and_get_key_store(+async fn get_account_and_key_store(state: SessionState,- merchant_id_or_profile_id: String,+ merchant_id: common_utils::id_type::MerchantId,+ profile_id: Option<String>,) -> errors::RouterResult<(MerchantAccountOrBusinessProfile, domain::MerchantKeyStore)> {let store = state.store.as_ref();let key_manager_state = &(&state).into();- let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from(- merchant_id_or_profile_id.clone(),- ))- .change_context(errors::ApiErrorResponse::InvalidDataValue {- field_name: "merchant_id",- })?;- match store+ let merchant_key_store = store.get_merchant_key_store_by_merchant_id(key_manager_state,&merchant_id,&store.get_master_key().to_vec().into(),).await- {- // Since a merchant key store was found with `merchant_id` = `merchant_id_or_profile_id`,- // `merchant_id_or_profile_id` is a valid merchant ID.- // Find a merchant account having `merchant_id` = `merchant_id_or_profile_id`.- Ok(key_store) => {- let merchant_account = store- .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)- .await- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;-- Ok((- MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account),- key_store,- ))- }-- /*- // Since no merchant key store was found with `merchant_id` = `merchant_id_or_profile_id`,- // `merchant_id_or_profile_id` is not a valid merchant ID.- // Assuming that `merchant_id_or_profile_id` is a business profile ID, try to find a- // business profile having `profile_id` = `merchant_id_or_profile_id`.- Err(error) if error.current_context().is_db_not_found() => {- router_env::logger::debug!(- ?error,- %merchant_id_or_profile_id,- "Failed to find merchant key store for the specified merchant ID or business profile ID"- );+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;+ match profile_id {+ // If profile ID is specified, return business profile, since a business profile is more+ // specific than a merchant account.+ Some(profile_id) => {let business_profile = store- .find_business_profile_by_profile_id(&merchant_id_or_profile_id)+ .find_business_profile_by_merchant_id_profile_id(+ key_manager_state,+ &merchant_key_store,+ &merchant_id,+ &profile_id,+ ).await+ .attach_printable_lazy(|| {+ format!(+ "Failed to find business profile by merchant_id `{merchant_id:?}` and profile_id `{profile_id}`. \+ The merchant_id associated with the business profile `{profile_id}` may be \+ different than the merchant_id specified (`{merchant_id:?}`)."+ )+ }).to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {- id: merchant_id_or_profile_id,+ id: profile_id,})?;- let key_store = store- .get_merchant_key_store_by_merchant_id(+ Ok((+ MerchantAccountOrBusinessProfile::BusinessProfile(business_profile),+ merchant_key_store,+ ))+ }++ None => {+ let merchant_account = store+ .find_merchant_account_by_merchant_id(key_manager_state,- &business_profile.merchant_id,- &store.get_master_key().to_vec().into(),+ &merchant_id,+ &merchant_key_store,).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;Ok((- MerchantAccountOrBusinessProfile::BusinessProfile(business_profile),- key_store,+ MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account),+ merchant_key_store,))}- */- Err(error) => Err(error)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to find merchant key store by merchant ID"),}}diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rsindex 7b7de43d60..ed178f275f 100644--- a/crates/router/src/db/business_profile.rs+++ b/crates/router/src/db/business_profile.rs@@ -36,6 +36,14 @@ whereprofile_id: &str,) -> CustomResult<domain::BusinessProfile, errors::StorageError>;+ async fn find_business_profile_by_merchant_id_profile_id(+ &self,+ key_manager_state: &KeyManagerState,+ merchant_key_store: &domain::MerchantKeyStore,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &str,+ ) -> CustomResult<domain::BusinessProfile, errors::StorageError>;+async fn find_business_profile_by_profile_name_merchant_id(&self,key_manager_state: &KeyManagerState,@@ -112,6 +120,26 @@ impl BusinessProfileInterface for Store {.change_context(errors::StorageError::DecryptionError)}+ async fn find_business_profile_by_merchant_id_profile_id(+ &self,+ key_manager_state: &KeyManagerState,+ merchant_key_store: &domain::MerchantKeyStore,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &str,+ ) -> CustomResult<domain::BusinessProfile, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ storage::BusinessProfile::find_by_merchant_id_profile_id(&conn, merchant_id, profile_id)+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))?+ .convert(+ key_manager_state,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ }+#[instrument(skip_all)]async fn find_business_profile_by_profile_name_merchant_id(&self,@@ -262,6 +290,42 @@ impl BusinessProfileInterface for MockDb {)}+ async fn find_business_profile_by_merchant_id_profile_id(+ &self,+ key_manager_state: &KeyManagerState,+ merchant_key_store: &domain::MerchantKeyStore,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &str,+ ) -> CustomResult<domain::BusinessProfile, errors::StorageError> {+ self.business_profiles+ .lock()+ .await+ .iter()+ .find(|business_profile| {+ business_profile.merchant_id == *merchant_id+ && business_profile.profile_id == profile_id+ })+ .cloned()+ .async_map(|business_profile| async {+ business_profile+ .convert(+ key_manager_state,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ })+ .await+ .transpose()?+ .ok_or(+ errors::StorageError::ValueNotFound(format!(+ "No business profile found for merchant_id = {merchant_id:?} and profile_id = {profile_id}"+ ))+ .into(),+ )+ }+async fn update_business_profile_by_profile_id(&self,key_manager_state: &KeyManagerState,diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rsindex 3b0f789cf0..edd1eecff9 100644--- a/crates/router/src/db/events.rs+++ b/crates/router/src/db/events.rs@@ -84,14 +84,6 @@ wheremerchant_key_store: &domain::MerchantKeyStore,) -> CustomResult<Vec<domain::Event>, errors::StorageError>;- async fn list_events_by_profile_id_initial_attempt_id(- &self,- state: &KeyManagerState,- profile_id: &str,- initial_attempt_id: &str,- merchant_key_store: &domain::MerchantKeyStore,- ) -> CustomResult<Vec<domain::Event>, errors::StorageError>;-async fn update_event_by_merchant_id_event_id(&self,state: &KeyManagerState,@@ -338,37 +330,6 @@ impl EventInterface for Store {.await}- #[instrument(skip_all)]- async fn list_events_by_profile_id_initial_attempt_id(- &self,- state: &KeyManagerState,- profile_id: &str,- initial_attempt_id: &str,- merchant_key_store: &domain::MerchantKeyStore,- ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {- let conn = connection::pg_connection_read(self).await?;- storage::Event::list_by_profile_id_initial_attempt_id(&conn, profile_id, initial_attempt_id)- .await- .map_err(|error| report!(errors::StorageError::from(error)))- .async_and_then(|events| async {- let mut domain_events = Vec::with_capacity(events.len());- for event in events.into_iter() {- domain_events.push(- event- .convert(- state,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(errors::StorageError::DecryptionError)?,- );- }- Ok(domain_events)- })- .await- }-#[instrument(skip_all)]async fn update_event_by_merchant_id_event_id(&self,@@ -695,39 +656,6 @@ impl EventInterface for MockDb {Ok(domain_events)}- async fn list_events_by_profile_id_initial_attempt_id(- &self,- state: &KeyManagerState,- profile_id: &str,- initial_attempt_id: &str,- merchant_key_store: &domain::MerchantKeyStore,- ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {- let locked_events = self.events.lock().await;- let events = locked_events- .iter()- .filter(|event| {- event.business_profile_id == Some(profile_id.to_owned())- && event.initial_attempt_id == Some(initial_attempt_id.to_owned())- })- .cloned()- .collect::<Vec<_>>();- let mut domain_events = Vec::with_capacity(events.len());-- for event in events {- let domain_event = event- .convert(- state,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(errors::StorageError::DecryptionError)?;- domain_events.push(domain_event);- }-- Ok(domain_events)- }-async fn update_event_by_merchant_id_event_id(&self,state: &KeyManagerState,diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 31b9ffcd7f..ddae52c243 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -668,23 +668,6 @@ impl EventInterface for KafkaStore {.await}- async fn list_events_by_profile_id_initial_attempt_id(- &self,- state: &KeyManagerState,- profile_id: &str,- initial_attempt_id: &str,- merchant_key_store: &domain::MerchantKeyStore,- ) -> CustomResult<Vec<domain::Event>, errors::StorageError> {- self.diesel_store- .list_events_by_profile_id_initial_attempt_id(- state,- profile_id,- initial_attempt_id,- merchant_key_store,- )- .await- }-async fn update_event_by_merchant_id_event_id(&self,state: &KeyManagerState,@@ -2270,6 +2253,23 @@ impl BusinessProfileInterface for KafkaStore {.await}+ async fn find_business_profile_by_merchant_id_profile_id(+ &self,+ key_manager_state: &KeyManagerState,+ merchant_key_store: &domain::MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ profile_id: &str,+ ) -> CustomResult<domain::BusinessProfile, errors::StorageError> {+ self.diesel_store+ .find_business_profile_by_merchant_id_profile_id(+ key_manager_state,+ merchant_key_store,+ merchant_id,+ profile_id,+ )+ .await+ }+async fn update_business_profile_by_profile_id(&self,key_manager_state: &KeyManagerState,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 614774ebb0..a705c60300 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1762,7 +1762,7 @@ pub struct WebhookEvents;#[cfg(feature = "olap")]impl WebhookEvents {pub fn server(config: AppState) -> Scope {- web::scope("/events/{merchant_id_or_profile_id}")+ web::scope("/events/{merchant_id}").app_data(web::Data::new(config)).service(web::resource("").route(web::get().to(list_initial_webhook_delivery_attempts))).service(diff --git a/crates/router/src/routes/webhook_events.rs b/crates/router/src/routes/webhook_events.rsindex 548ee65259..d5150ad1fe 100644--- a/crates/router/src/routes/webhook_events.rs+++ b/crates/router/src/routes/webhook_events.rs@@ -19,11 +19,11 @@ pub async fn list_initial_webhook_delivery_attempts(query: web::Query<EventListConstraints>,) -> impl Responder {let flow = Flow::WebhookEventInitialDeliveryAttemptList;- let merchant_id_or_profile_id = path.into_inner();+ let merchant_id = path.into_inner();let constraints = query.into_inner();let request_internal = EventListRequestInternal {- merchant_id_or_profile_id: merchant_id_or_profile_id.get_string_repr().to_string(),+ merchant_id: merchant_id.clone(),constraints,};@@ -35,14 +35,14 @@ pub async fn list_initial_webhook_delivery_attempts(|state, _, request_internal, _| {webhook_events::list_initial_delivery_attempts(state,- request_internal.merchant_id_or_profile_id,+ request_internal.merchant_id,request_internal.constraints,)},auth::auth_type(&auth::AdminApiAuth,&auth::JWTAuthMerchantFromRoute {- merchant_id: merchant_id_or_profile_id,+ merchant_id,required_permission: Permission::WebhookEventRead,},req.headers(),@@ -59,10 +59,10 @@ pub async fn list_webhook_delivery_attempts(path: web::Path<(common_utils::id_type::MerchantId, String)>,) -> impl Responder {let flow = Flow::WebhookEventDeliveryAttemptList;- let (merchant_id_or_profile_id, initial_attempt_id) = path.into_inner();+ let (merchant_id, initial_attempt_id) = path.into_inner();let request_internal = WebhookDeliveryAttemptListRequestInternal {- merchant_id_or_profile_id: merchant_id_or_profile_id.get_string_repr().to_string(),+ merchant_id: merchant_id.clone(),initial_attempt_id,};@@ -74,14 +74,14 @@ pub async fn list_webhook_delivery_attempts(|state, _, request_internal, _| {webhook_events::list_delivery_attempts(state,- request_internal.merchant_id_or_profile_id,+ request_internal.merchant_id,request_internal.initial_attempt_id,)},auth::auth_type(&auth::AdminApiAuth,&auth::JWTAuthMerchantFromRoute {- merchant_id: merchant_id_or_profile_id,+ merchant_id,required_permission: Permission::WebhookEventRead,},req.headers(),@@ -98,10 +98,10 @@ pub async fn retry_webhook_delivery_attempt(path: web::Path<(common_utils::id_type::MerchantId, String)>,) -> impl Responder {let flow = Flow::WebhookEventDeliveryRetry;- let (merchant_id_or_profile_id, event_id) = path.into_inner();+ let (merchant_id, event_id) = path.into_inner();let request_internal = WebhookDeliveryRetryRequestInternal {- merchant_id_or_profile_id: merchant_id_or_profile_id.get_string_repr().to_string(),+ merchant_id: merchant_id.clone(),event_id,};@@ -113,14 +113,14 @@ pub async fn retry_webhook_delivery_attempt(|state, _, request_internal, _| {webhook_events::retry_delivery_attempt(state,- request_internal.merchant_id_or_profile_id,+ request_internal.merchant_id,request_internal.event_id,)},auth::auth_type(&auth::AdminApiAuth,&auth::JWTAuthMerchantFromRoute {- merchant_id: merchant_id_or_profile_id,+ merchant_id,required_permission: Permission::WebhookEventWrite,},req.headers(),diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 7e7e7b8b40..30857f797f 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -1033,70 +1033,6 @@ where}}-/*-pub struct JWTAuthMerchantOrProfileFromRoute {- pub merchant_id_or_profile_id: String,- pub required_permission: Permission,-}--#[async_trait]-impl<A> AuthenticateAndFetch<(), A> for JWTAuthMerchantOrProfileFromRoute-where- A: SessionStateInfo + Sync,-{- async fn authenticate_and_fetch(- &self,- request_headers: &HeaderMap,- state: &A,- ) -> RouterResult<((), AuthenticationType)> {- let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;- if payload.check_in_blacklist(state).await? {- return Err(errors::ApiErrorResponse::InvalidJwtToken.into());- }-- let permissions = authorization::get_permissions(state, &payload).await?;- authorization::check_authorization(&self.required_permission, &permissions)?;-- // Check if token has access to MerchantId that has been requested through path or query param- if payload.merchant_id.get_string_repr() == self.merchant_id_or_profile_id {- return Ok((- (),- AuthenticationType::MerchantJwt {- merchant_id: payload.merchant_id,- user_id: Some(payload.user_id),- },- ));- }-- // Route did not contain the merchant ID in present JWT, check if it corresponds to a- // business profile- let business_profile = state- .store()- .find_business_profile_by_profile_id(&self.merchant_id_or_profile_id)- .await- // Return access forbidden if business profile not found- .to_not_found_response(errors::ApiErrorResponse::AccessForbidden {- resource: self.merchant_id_or_profile_id.clone(),- })- .attach_printable("Could not find business profile specified in route")?;-- // Check if merchant (from JWT) has access to business profile that has been requested- // through path or query param- if payload.merchant_id == business_profile.merchant_id {- Ok((- (),- AuthenticationType::MerchantJwt {- merchant_id: payload.merchant_id,- user_id: Some(payload.user_id),- },- ))- } else {- Err(report!(errors::ApiErrorResponse::InvalidJwtToken))- }- }-}-*/-pub async fn parse_jwt_payload<A, T>(headers: &HeaderMap, state: &A) -> RouterResult<T>whereT: serde::de::DeserializeOwned,