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
fix(api): enforce merchant and profile isolation (#15049)
Sakil Mostak08c2e710f1fb
diff --git a/crates/diesel_models/src/query/business_profile.rs b/crates/diesel_models/src/query/business_profile.rsindex 9bc4f7968d..da0810179b 100644--- a/crates/diesel_models/src/query/business_profile.rs+++ b/crates/diesel_models/src/query/business_profile.rs@@ -22,12 +22,18 @@ impl Profile {conn: &DatabaseConnectionWithContext<'_>,business_profile: ProfileUpdateInternal,) -> StorageResult<Self> {- match Box::pin(generics::generic_update_by_id::<+ match Box::pin(generics::generic_update_with_unique_predicate_get_result::<<Self as HasTable>::Table,_,_,_,- >(conn, self.get_id().to_owned(), business_profile))+ >(+ conn,+ dsl::merchant_id+ .eq(self.merchant_id.to_owned())+ .and(dsl_identifier.eq(self.get_id().to_owned())),+ business_profile,+ )).await{Err(error) => match error.current_context() {diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex b124fa71c6..7cd5b79d29 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -4122,11 +4122,20 @@ pub async fn retrieve_profile(id: profile_id.get_string_repr().to_owned(),})?;- Ok(service_api::ApplicationResponse::Json(- api_models::admin::ProfileResponse::foreign_try_from(business_profile)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse business profile details")?,- ))+ // Cache hits must preserve the same ownership constraint as the database query.+ match business_profile {+ business_profile if business_profile.merchant_id == merchant_id => {+ Ok(service_api::ApplicationResponse::Json(+ api_models::admin::ProfileResponse::foreign_try_from(business_profile)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse business profile details")?,+ ))+ }+ _ => Err(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ }+ .into()),+ }}pub async fn delete_profile(@@ -4858,50 +4867,53 @@ pub async fn extended_card_info_toggle(pub async fn connector_agnostic_mit_toggle(state: SessionState,+ processor: domain::Processor,merchant_id: &id_type::MerchantId,profile_id: &id_type::ProfileId,connector_agnostic_mit_choice: admin_types::ConnectorAgnosticMitChoice,) -> RouterResponse<admin_types::ConnectorAgnosticMitChoice> {let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )- .await- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)- .attach_printable("Error while fetching the key store by merchant_id")?;- let business_profile = db- .find_business_profile_by_profile_id(&key_store, profile_id)- .await- .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;+ match processor.get_account().get_id() {+ processor_merchant_id if processor_merchant_id == merchant_id => {+ let key_store = processor.get_key_store();- if business_profile.merchant_id != *merchant_id {- Err(errors::ApiErrorResponse::AccessForbidden {- resource: profile_id.get_string_repr().to_owned(),- })?- }+ let business_profile = db+ .find_business_profile_by_merchant_id_profile_id(key_store, merchant_id, profile_id)+ .await+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;- if business_profile.is_connector_agnostic_mit_enabled- != Some(connector_agnostic_mit_choice.enabled)- {- let profile_update = domain::ProfileUpdate::ConnectorAgnosticMitUpdate {- is_connector_agnostic_mit_enabled: connector_agnostic_mit_choice.enabled,- };+ if business_profile.merchant_id != *merchant_id {+ Err(errors::ApiErrorResponse::AccessForbidden {+ resource: profile_id.get_string_repr().to_owned(),+ })?+ }- db.update_profile_by_profile_id(&key_store, business_profile, profile_update)- .await- .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;- }+ if business_profile.is_connector_agnostic_mit_enabled+ != Some(connector_agnostic_mit_choice.enabled)+ {+ let profile_update = domain::ProfileUpdate::ConnectorAgnosticMitUpdate {+ is_connector_agnostic_mit_enabled: connector_agnostic_mit_choice.enabled,+ };- Ok(service_api::ApplicationResponse::Json(- connector_agnostic_mit_choice,- ))+ db.update_profile_by_profile_id(key_store, business_profile, profile_update)+ .await+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;+ }++ Ok(service_api::ApplicationResponse::Json(+ connector_agnostic_mit_choice,+ ))+ }+ _ => Err(errors::ApiErrorResponse::AccessForbidden {+ resource: profile_id.get_string_repr().to_owned(),+ }+ .into()),+ }}pub async fn transfer_key_store_to_key_manager(diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex dc4b4a68ed..f12b0e5090 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -764,6 +764,7 @@ pub async fn payouts_create_core(pub async fn payouts_confirm_core(state: SessionState,platform: domain::Platform,+ profile_id: Option<id_type::ProfileId>,req: payouts::PayoutCreateRequest,header_payload: HeaderPayload,) -> RouterResponse<payouts::PayoutCreateResponse> {@@ -774,7 +775,7 @@ pub async fn payouts_confirm_core(let mut payout_data = Box::pin(make_payout_data(&state,&platform,- None,+ profile_id,&payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())),&state.locale,))@@ -833,6 +834,7 @@ pub async fn payouts_confirm_core(pub async fn payouts_update_core(state: SessionState,platform: domain::Platform,+ profile_id: Option<id_type::ProfileId>,req: payouts::PayoutCreateRequest,header_payload: HeaderPayload,) -> RouterResponse<payouts::PayoutCreateResponse> {@@ -844,7 +846,7 @@ pub async fn payouts_update_core(let mut payout_data = Box::pin(make_payout_data(&state,&platform,- None,+ profile_id,&payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())),&state.locale,))@@ -964,13 +966,14 @@ pub async fn payouts_retrieve_core(pub async fn payouts_cancel_core(state: SessionState,platform: domain::Platform,+ profile_id: Option<id_type::ProfileId>,header_payload: HeaderPayload,req: payouts::PayoutActionRequest,) -> RouterResponse<payouts::PayoutCreateResponse> {let mut payout_data = Box::pin(make_payout_data(&state,&platform,- None,+ profile_id,&payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),&state.locale,))@@ -1075,13 +1078,14 @@ pub async fn payouts_cancel_core(pub async fn payouts_fulfill_core(state: SessionState,platform: domain::Platform,+ profile_id: Option<id_type::ProfileId>,header_payload: HeaderPayload,req: payouts::PayoutActionRequest,) -> RouterResponse<payouts::PayoutCreateResponse> {let mut payout_data = Box::pin(make_payout_data(&state,&platform,- None,+ profile_id,&payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),&state.locale,))@@ -3888,6 +3892,23 @@ pub async fn make_payout_data(core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &payouts)?;+ if let payouts::PayoutRequest::PayoutCreateRequest(request) = req {+ validator::validate_payout_condition(+ request+ .merchant_id+ .as_ref()+ .is_some_and(|request_merchant_id| request_merchant_id != merchant_id),+ "Payout merchant does not match the authenticated merchant",+ )?;+ validator::validate_payout_condition(+ request+ .profile_id+ .as_ref()+ .is_some_and(|request_profile_id| request_profile_id != &payouts.profile_id),+ "Payout profile does not match the existing payout",+ )?;+ }+let payout_attempt_id =utils::get_payout_attempt_id(payouts.payout_id.get_string_repr(), payouts.attempt_count);diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rsindex 46b7b8ac36..5b6155d2d6 100644--- a/crates/router/src/core/verification.rs+++ b/crates/router/src/core/verification.rs@@ -15,6 +15,14 @@ pub async fn verify_merchant_creds_for_applepay(profile_id: Option<common_utils::id_type::ProfileId>,) -> CustomResult<services::ApplicationResponse<ApplepayMerchantResponse>, errors::ApiErrorResponse>{+ let (key_store, merchant_connector_account) = utils::get_apple_pay_merchant_connector_account(+ &state,+ &merchant_id,+ profile_id,+ &body.merchant_connector_account_id,+ )+ .await?;+let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner();let applepay_internal_merchant_identifier = applepay_merchant_configs@@ -60,12 +68,11 @@ pub async fn verify_merchant_creds_for_applepay(// Error is already loggedmatch applepay_response {Ok(_) => {- utils::check_existence_and_add_domain_to_db(+ utils::add_domain_to_apple_pay_merchant_connector_account(&state,- merchant_id,- profile_id,- body.merchant_connector_account_id.clone(),- body.domain_names.clone(),+ &key_store,+ merchant_connector_account,+ body.domain_names,).await.change_context(errors::ApiErrorResponse::InternalServerError)?;@@ -88,34 +95,21 @@ pub async fn verify_merchant_creds_for_applepay(pub async fn get_verified_apple_domains_with_mid_mca_id(state: SessionState,merchant_id: common_utils::id_type::MerchantId,+ profile_id: Option<common_utils::id_type::ProfileId>,merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,) -> CustomResult<services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>,errors::ApiErrorResponse,> {- let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())- .await- .change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?;-- #[cfg(feature = "v1")]- let verified_domains = db- .find_by_merchant_connector_account_merchant_id_merchant_connector_id(- &merchant_id,- &merchant_connector_id,- &key_store,- )- .await- .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?- .applepay_verified_domains- .unwrap_or_default();+ let (_, merchant_connector_account) = utils::get_apple_pay_merchant_connector_account(+ &state,+ &merchant_id,+ profile_id,+ &merchant_connector_id,+ )+ .await?;- #[cfg(feature = "v2")]- let verified_domains = db- .find_merchant_connector_account_by_id(&merchant_connector_id, &key_store)- .await- .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?+ let verified_domains = merchant_connector_account.applepay_verified_domains.unwrap_or_default();diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rsindex e9e105cce9..2f24f53f7e 100644--- a/crates/router/src/core/verification/utils.rs+++ b/crates/router/src/core/verification/utils.rs@@ -15,43 +15,61 @@ use crate::{types::{self, domain, storage},};-pub async fn check_existence_and_add_domain_to_db(+pub async fn get_apple_pay_merchant_connector_account(state: &SessionState,- merchant_id: common_utils::id_type::MerchantId,+ merchant_id: &common_utils::id_type::MerchantId,profile_id_from_auth_layer: Option<common_utils::id_type::ProfileId>,- merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,- domain_from_req: Vec<String>,-) -> CustomResult<Vec<String>, errors::ApiErrorResponse> {+ merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,+) -> CustomResult<+ (domain::MerchantKeyStore, domain::MerchantConnectorAccount),+ errors::ApiErrorResponse,+> {let key_store = state.store.get_merchant_key_store_by_merchant_id(- &merchant_id,+ merchant_id,&state.store.get_master_key().to_vec().into(),).await- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;#[cfg(feature = "v1")]let merchant_connector_account = state.store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(- &merchant_id,- &merchant_connector_id,+ merchant_id,+ merchant_connector_id,&key_store,).await- .change_context(errors::ApiErrorResponse::InternalServerError)?;+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;#[cfg(feature = "v2")]let merchant_connector_account = state.store- .find_merchant_connector_account_by_id(&merchant_connector_id, &key_store)+ .find_merchant_connector_account_by_id(merchant_connector_id, &key_store).await- .change_context(errors::ApiErrorResponse::InternalServerError)?;- utils::validate_profile_id_from_auth_layer(- profile_id_from_auth_layer,- &merchant_connector_account,- )?;+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;++ match &merchant_connector_account.merchant_id {+ merchant_connector_account_id if merchant_connector_account_id == merchant_id => {+ utils::validate_profile_id_from_auth_layer(+ profile_id_from_auth_layer,+ &merchant_connector_account,+ )?;++ Ok((key_store, merchant_connector_account))+ }+ _ => Err(errors::ApiErrorResponse::ResourceIdNotFound.into()),+ }+}++pub async fn add_domain_to_apple_pay_merchant_connector_account(+ state: &SessionState,+ key_store: &domain::MerchantKeyStore,+ merchant_connector_account: domain::MerchantConnectorAccount,+ domain_from_req: Vec<String>,+) -> CustomResult<Vec<String>, errors::ApiErrorResponse> {let mut already_verified_domains = merchant_connector_account.applepay_verified_domains.clone()@@ -99,19 +117,20 @@ pub async fn check_existence_and_add_domain_to_db(additional_merchant_data: Box::new(None),feature_metadata: Box::new(None),};+ let merchant_connector_id = merchant_connector_account.get_id();state.store.update_merchant_connector_account(merchant_connector_account,updated_mca.foreign_into(),- &key_store,+ key_store,).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| {format!(- "Failed while updating MerchantConnectorAccount: id: {merchant_connector_id:?}",-+ "Failed while updating MerchantConnectorAccount: id: {:?}",+ merchant_connector_id,)})?;diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rsindex 601147bf27..e520f0ed13 100644--- a/crates/router/src/routes/payouts.rs+++ b/crates/router/src/routes/payouts.rs@@ -27,6 +27,18 @@ use crate::{types::{api::payouts as payout_types, transformers::ForeignTryFrom},};+#[cfg(feature = "v1")]+fn get_authenticated_profile_id(auth: &auth::AuthenticationData) -> Option<id_type::ProfileId> {+ auth.profile+ .as_ref()+ .map(|profile| profile.get_id().clone())+}++#[cfg(feature = "v2")]+fn get_authenticated_profile_id(auth: &auth::AuthenticationData) -> Option<id_type::ProfileId> {+ Some(auth.profile.get_id().clone())+}+/// Payouts - Create#[cfg(feature = "v1")]#[instrument(skip_all, fields(flow = ?Flow::PayoutsCreate))]@@ -153,7 +165,14 @@ pub async fn payouts_update(&req,payout_update_payload,|state, auth: auth::AuthenticationData, req, _| {- payouts_update_core(state, auth.platform, req, header_payload.clone())+ let profile_id = get_authenticated_profile_id(&auth);+ payouts_update_core(+ state,+ auth.platform,+ profile_id,+ req,+ header_payload.clone(),+ )},&auth::HeaderAuth(auth::ApiKeyAuth {allow_connected_scope_operation: false,@@ -217,12 +236,20 @@ pub async fn payouts_confirm(&req,payload,|state, auth, mut req, _| {+ let profile_id = get_authenticated_profile_id(&auth);+#[cfg(feature = "v1")]if let Some(client_secret) = auth.client_secret {req.client_secret = Some(client_secret);}- payouts_confirm_core(state, auth.platform, req, header_payload.clone())+ payouts_confirm_core(+ state,+ auth.platform,+ profile_id,+ req,+ header_payload.clone(),+ )},&*auth_type,locking_action,@@ -280,7 +307,14 @@ pub async fn payouts_cancel(&req,payload,|state, auth: auth::AuthenticationData, req, _| {- payouts_cancel_core(state, auth.platform, header_payload.clone(), req)+ let profile_id = get_authenticated_profile_id(&auth);+ payouts_cancel_core(+ state,+ auth.platform,+ profile_id,+ header_payload.clone(),+ req,+ )},&auth::HeaderAuth(auth::ApiKeyAuth {allow_connected_scope_operation: false,@@ -314,7 +348,14 @@ pub async fn payouts_fulfill(&req,payload,|state, auth: auth::AuthenticationData, req, _| {- payouts_fulfill_core(state, auth.platform, header_payload.clone(), req)+ let profile_id = get_authenticated_profile_id(&auth);+ payouts_fulfill_core(+ state,+ auth.platform,+ profile_id,+ header_payload.clone(),+ req,+ )},&auth::HeaderAuth(auth::ApiKeyAuth {allow_connected_scope_operation: false,diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rsindex 02140258b4..65444896d1 100644--- a/crates/router/src/routes/profiles.rs+++ b/crates/router/src/routes/profiles.rs@@ -508,8 +508,14 @@ pub async fn toggle_connector_agnostic_mit(state,&req,json_payload.into_inner(),- |state, _: auth::AuthenticationData, req, _| {- connector_agnostic_mit_toggle(state, &merchant_id, &profile_id, req)+ |state, auth_data: auth::AuthenticationData, req, _| {+ connector_agnostic_mit_toggle(+ state,+ auth_data.platform.get_processor().clone(),+ &merchant_id,+ &profile_id,+ req,+ )},auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth {diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rsindex 0b5cd8b1a0..07cba3abde 100644--- a/crates/router/src/routes/verification.rs+++ b/crates/router/src/routes/verification.rs@@ -4,7 +4,7 @@ use router_env::{instrument, tracing, Flow};use super::app::AppState;use crate::{- core::{api_locking, verification},+ core::{api_locking, errors, verification},services::{api, authentication as auth, authorization::permissions::Permission},};@@ -24,12 +24,21 @@ pub async fn apple_pay_merchant_registration(&req,json_payload.into_inner(),|state, auth: auth::AuthenticationData, body, _| {- verification::verify_merchant_creds_for_applepay(- state.clone(),- body,- merchant_id.clone(),- auth.profile.map(|profile| profile.get_id().clone()),- )+ let merchant_id = merchant_id.clone();+ async move {+ match auth.platform.get_processor().get_account().get_id() {+ authenticated_merchant_id if authenticated_merchant_id == &merchant_id => {+ verification::verify_merchant_creds_for_applepay(+ state.clone(),+ body,+ merchant_id,+ auth.profile.map(|profile| profile.get_id().clone()),+ )+ .await+ }+ _ => Err(errors::ApiErrorResponse::Unauthorized.into()),+ }+ }},auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth {@@ -64,12 +73,21 @@ pub async fn apple_pay_merchant_registration(&req,json_payload.into_inner(),|state, auth: auth::AuthenticationData, body, _| {- verification::verify_merchant_creds_for_applepay(- state.clone(),- body,- merchant_id.clone(),- Some(auth.profile.get_id().clone()),- )+ let merchant_id = merchant_id.clone();+ async move {+ match auth.platform.get_processor().get_account().get_id() {+ authenticated_merchant_id if authenticated_merchant_id == &merchant_id => {+ verification::verify_merchant_creds_for_applepay(+ state.clone(),+ body,+ merchant_id,+ Some(auth.profile.get_id().clone()),+ )+ .await+ }+ _ => Err(errors::ApiErrorResponse::Unauthorized.into()),+ }+ }},auth::auth_type(&auth::V2ApiKeyAuth {@@ -103,12 +121,28 @@ pub async fn retrieve_apple_pay_verified_domains(state,&req,merchant_id.clone(),- |state, _: auth::AuthenticationData, _, _| {- verification::get_verified_apple_domains_with_mid_mca_id(- state,- merchant_id.to_owned(),- mca_id.clone(),- )+ |state, auth: auth::AuthenticationData, _, _| {+ let merchant_id = merchant_id.clone();+ let mca_id = mca_id.clone();+ async move {+ match auth.platform.get_processor().get_account().get_id() {+ authenticated_merchant_id if authenticated_merchant_id == &merchant_id => {+ #[cfg(feature = "v1")]+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());+ #[cfg(feature = "v2")]+ let profile_id = Some(auth.profile.get_id().clone());++ verification::get_verified_apple_domains_with_mid_mca_id(+ state,+ merchant_id,+ profile_id,+ mca_id,+ )+ .await+ }+ _ => Err(errors::ApiErrorResponse::Unauthorized.into()),+ }+ }},auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth {diff --git a/crates/storage_impl/src/business_profile.rs b/crates/storage_impl/src/business_profile.rsindex bb785cd66d..d59e4a5b12 100644--- a/crates/storage_impl/src/business_profile.rs+++ b/crates/storage_impl/src/business_profile.rs@@ -26,12 +26,32 @@ use crate::{CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,};-/// Cache key for a profile, shared by both the profile-scoped and merchant-scoped lookups.+/// Cache key for a profile.+///+/// Profile IDs are globally unique, so ownership is validated on the cached row instead of being+/// encoded in this key. Keeping the established key format makes cache reads and invalidations+/// compatible across a rolling deployment.#[cfg(feature = "accounts_cache")]fn profile_cache_key(profile_id: &common_utils::id_type::ProfileId) -> String {format!("business_profile_{}", profile_id.get_string_repr())}+#[cfg(feature = "accounts_cache")]+fn validate_cached_profile_ownership(+ cached_merchant_id: &common_utils::id_type::MerchantId,+ expected_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+) -> CustomResult<(), StorageError> {+ (cached_merchant_id == expected_merchant_id)+ .then_some(())+ .ok_or_else(|| {+ report!(StorageError::ValueNotFound(format!(+ "No business profile found for merchant_id = {expected_merchant_id:?} and \+ profile_id = {profile_id:?}"+ )))+ })+}+/// Invalidates the cached profile on a best-effort basis.////// Callers invoke this only after their database write has committed, so a redis failure must not@@ -193,9 +213,13 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {) -> CustomResult<domain::Profile, StorageError> {let fetch_func = || async {let conn = pg_accounts_connection_read(self).await?;- diesel::Profile::find_by_profile_id(&conn, profile_id)- .await- .map_err(|error| report!(StorageError::from(error)))+ diesel::Profile::find_by_merchant_id_profile_id(+ &conn,+ &merchant_key_store.merchant_id,+ profile_id,+ )+ .await+ .map_err(|error| report!(StorageError::from(error)))};let state = self.get_keymanager_state()@@ -216,20 +240,28 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {#[cfg(feature = "accounts_cache")]{- Box::pin(cache::get_or_populate_in_memory_redis(+ let profile = Box::pin(cache::get_or_populate_in_memory_redis(self,&profile_cache_key(profile_id),fetch_func(),CacheId::Accounts,))- .await?- .convert(- state,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(StorageError::DecryptionError)+ .await?;++ validate_cached_profile_ownership(+ &profile.merchant_id,+ &merchant_key_store.merchant_id,+ profile_id,+ )?;++ profile+ .convert(+ state,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)}}@@ -264,20 +296,24 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {#[cfg(feature = "accounts_cache")]{- Box::pin(cache::get_or_populate_in_memory_redis(+ let profile = Box::pin(cache::get_or_populate_in_memory_redis(self,&profile_cache_key(profile_id),fetch_func(),CacheId::Accounts,))- .await?- .convert(- state,- merchant_key_store.key.get_inner(),- merchant_key_store.merchant_id.clone().into(),- )- .await- .change_context(StorageError::DecryptionError)+ .await?;++ validate_cached_profile_ownership(&profile.merchant_id, merchant_id, profile_id)?;++ profile+ .convert(+ state,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)}}@@ -397,7 +433,10 @@ impl ProfileInterface for MockDb {.lock().await.iter()- .find(|business_profile| business_profile.get_id() == profile_id)+ .find(|business_profile| {+ business_profile.get_id() == profile_id+ && business_profile.merchant_id == merchant_key_store.merchant_id+ }).cloned().async_map(|business_profile| async {business_profile@@ -462,11 +501,15 @@ impl ProfileInterface for MockDb {profile_update: domain::ProfileUpdate,) -> CustomResult<domain::Profile, StorageError> {let profile_id = current_state.get_id().to_owned();+ let merchant_id = current_state.merchant_id.clone();self.business_profiles.lock().await.iter_mut()- .find(|business_profile| business_profile.get_id() == current_state.get_id())+ .find(|business_profile| {+ business_profile.get_id() == current_state.get_id()+ && business_profile.merchant_id == merchant_id+ }).async_map(|business_profile| async {let profile_updated = ProfileUpdateInternal::foreign_from(profile_update).apply_changeset(