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(payments): enforce authenticated payment scope (#15080)
Ayush Anandd07de03379c9
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 930a9199a7..f2fd3f6680 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -1054,7 +1054,7 @@"Payments"],"summary": "Payments - Confirm",- "description": "Confirms a payment intent that was previously created with `confirm: false`. This action attempts to authorize the payment with the payment processor.\n\nExpected status transitions after confirmation:\n- `succeeded`: If authorization is successful and `capture_method` is `automatic`.\n- `requires_capture`: If authorization is successful and `capture_method` is `manual`.\n- `failed`: If authorization fails.",+ "description": "Confirms a payment intent that was previously created with `confirm: false`. This action attempts to authorize the payment with the payment processor.\n\nExpected status transitions after confirmation:\n- `succeeded`: If authorization is successful and `capture_method` is `automatic`.\n- `requires_capture`: If authorization is successful and `capture_method` is `manual`.\n- `failed`: If authorization fails.\nProfile-restricted requests are authorized against the stored payment before payment-method\nprefetch, retry records, address updates, or other confirmation side effects.","operationId": "Confirm a Payment","parameters": [{@@ -1151,7 +1151,7 @@"Payments"],"summary": "Payments - Capture",- "description": "Captures the funds for a previously authorized payment intent where `capture_method` was set to `manual` and the payment is in a `requires_capture` state.\n\nUpon successful capture, the payment status usually transitions to `succeeded`.\nThe `amount_to_capture` can be specified in the request body; it must be less than or equal to the payment's `amount_capturable`. If omitted, the full capturable amount is captured.\n\nA payment must be in a capturable state (e.g., `requires_capture`). Attempting to capture an already `succeeded` (and fully captured) payment or one in an invalid state will lead to an error.\n",+ "description": "Captures the funds for a previously authorized payment intent where `capture_method` was set to `manual` and the payment is in a `requires_capture` state.\n\nUpon successful capture, the payment status usually transitions to `succeeded`.\nThe `amount_to_capture` can be specified in the request body; it must be less than or equal to the payment's `amount_capturable`. If omitted, the full capturable amount is captured.\n\nA payment must be in a capturable state (e.g., `requires_capture`). Attempting to capture an already `succeeded` (and fully captured) payment or one in an invalid state will lead to an error.\nWhen authentication restricts access to a profile, the payment must belong to that profile.\nThis authorization is checked before creating a capture record, including for multiple captures.\nPayments outside the authenticated merchant/profile scope are treated as not found.\n","operationId": "Capture a Payment","parameters": [{@@ -1215,6 +1215,16 @@}}}+ },+ "404": {+ "description": "Payment not found in the authenticated merchant/profile scope",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GenericErrorResponseOpenApi"+ }+ }+ }}},"security": [@@ -1277,7 +1287,7 @@"Payments"],"summary": "Payments - Cancel",- "description": "A Payment could can be cancelled when it is in one of these statuses: `requires_payment_method`, `requires_capture`, `requires_confirmation`, `requires_customer_action`.",+ "description": "A Payment could can be cancelled when it is in one of these statuses: `requires_payment_method`, `requires_capture`, `requires_confirmation`, `requires_customer_action`.\nProfile-restricted authentication can cancel only payments in that profile.\nPayments outside the authenticated merchant/profile scope are treated as not found before cancellation side effects.","operationId": "Cancel a Payment","parameters": [{@@ -1334,6 +1344,16 @@}}}+ },+ "404": {+ "description": "Payment not found in the authenticated merchant/profile scope",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GenericErrorResponseOpenApi"+ }+ }+ }}},"security": [diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rsindex 89ba099584..b20d2d1daf 100644--- a/crates/diesel_models/src/query/payment_intent.rs+++ b/crates/diesel_models/src/query/payment_intent.rs@@ -138,6 +138,23 @@ impl PaymentIntent {.await}+ #[cfg(feature = "v1")]+ pub async fn find_by_payment_id_processor_merchant_id_profile_id(+ conn: &DatabaseConnectionWithContext<'_>,+ payment_id: &common_utils::id_type::PaymentId,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::payment_id.eq(payment_id.to_owned()))+ .and(dsl::profile_id.eq(profile_id.to_owned())),+ )+ .await+ }+#[cfg(feature = "v2")]pub async fn find_optional_by_merchant_reference_id_merchant_id(conn: &DatabaseConnectionWithContext<'_>,diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rsindex 5e1020dc38..9b0dbbfee7 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs@@ -69,6 +69,17 @@ pub trait PaymentIntentInterface {merchant_key_store: &ProcessorKeyStore,storage_scheme: ProcessorStorageScheme,) -> error_stack::Result<PaymentIntent, Self::Error>;++ /// Retrieve a payment only when both its processor merchant and stored profile match.+ #[cfg(feature = "v1")]+ async fn find_payment_intent_by_payment_id_processor_merchant_id_profile_id(+ &self,+ payment_id: &id_type::PaymentId,+ processor_merchant_id: &ProcessorMerchantId,+ profile_id: &id_type::ProfileId,+ merchant_key_store: &ProcessorKeyStore,+ storage_scheme: ProcessorStorageScheme,+ ) -> error_stack::Result<PaymentIntent, Self::Error>;#[cfg(feature = "v2")]async fn find_payment_intent_by_merchant_reference_id_profile_id(&self,@@ -1860,6 +1871,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateIntpub enum PaymentIntentFetchConstraints {Single {payment_intent_id: id_type::PaymentId,+ profile_id: Option<Vec<id_type::ProfileId>>,},List(Box<PaymentIntentListParams>),}@@ -1867,10 +1879,9 @@ pub enum PaymentIntentFetchConstraints {#[cfg(feature = "v1")]impl PaymentIntentFetchConstraints {pub fn get_profile_id_list(&self) -> Option<Vec<id_type::ProfileId>> {- if let Self::List(pi_list_params) = self {- pi_list_params.profile_id.clone()- } else {- None+ match self {+ Self::Single { profile_id, .. } => profile_id.clone(),+ Self::List(pi_list_params) => pi_list_params.profile_id.clone(),}}}@@ -2107,7 +2118,10 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentFcustomer_email,} = value;if let Some(payment_intent_id) = payment_id {- Self::Single { payment_intent_id }+ Self::Single {+ payment_intent_id,+ profile_id: profile_id.map(|profile_id| vec![profile_id]),+ }} else {Self::List(Box::new(PaymentIntentListParams {offset,@@ -2163,7 +2177,10 @@ impl From<api_models::payments::PlatformPaymentListConstraints> for PaymentIntenorder,} = value;if let Some(payment_intent_id) = payment_id {- Self::Single { payment_intent_id }+ Self::Single {+ payment_intent_id,+ profile_id: profile_id.map(|profile_id| vec![profile_id]),+ }} else {Self::List(Box::new(PaymentIntentListParams {offset,@@ -2208,46 +2225,31 @@ wherefn try_from((constraints, auth_profile_id_list): (T, Option<Vec<id_type::ProfileId>>),) -> Result<Self, Self::Error> {- let payment_intent_constraints = Self::from(constraints);- if let Self::List(mut pi_list_params) = payment_intent_constraints {- let profile_id_from_request_body = pi_list_params.profile_id;- match (profile_id_from_request_body, auth_profile_id_list) {- (None, None) => pi_list_params.profile_id = None,- (None, Some(auth_profile_id_list)) => {- pi_list_params.profile_id = Some(auth_profile_id_list)- }- (Some(profile_id_from_request_body), None) => {- pi_list_params.profile_id = Some(profile_id_from_request_body)- }- (Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {- let profile_id_from_request_body_is_available_in_auth_profile_id_list =- profile_id_from_request_body- .iter()- .all(|profile_id| auth_profile_id_list.contains(profile_id));-- if profile_id_from_request_body_is_available_in_auth_profile_id_list {- pi_list_params.profile_id = Some(profile_id_from_request_body)- } else {- // This scenario is very unlikely to happen- let inaccessible_profile_ids: Vec<_> = profile_id_from_request_body- .iter()- .filter(|profile_id| !auth_profile_id_list.contains(profile_id))- .collect();- return Err(error_stack::Report::new(- errors::api_error_response::ApiErrorResponse::PreconditionFailed {- message: format!(- "Access not available for the given profile_id {inaccessible_profile_ids:?}",-- ),- },- ));- }- }+ let mut payment_intent_constraints = Self::from(constraints);+ let profile_id = match &mut payment_intent_constraints {+ Self::Single { profile_id, .. } => profile_id,+ Self::List(params) => &mut params.profile_id,+ };+ match (profile_id.as_ref(), auth_profile_id_list) {+ (None, Some(auth_profile_ids)) => *profile_id = Some(auth_profile_ids),+ (Some(requested_profile_ids), Some(auth_profile_ids)) => {+ let inaccessible_profile_ids: Vec<_> = requested_profile_ids+ .iter()+ .filter(|profile_id| !auth_profile_ids.contains(profile_id))+ .collect();+ common_utils::fp_utils::when(!inaccessible_profile_ids.is_empty(), || {+ Err(error_stack::Report::new(+ errors::api_error_response::ApiErrorResponse::PreconditionFailed {+ message: format!(+ "Access not available for the given profile_id {inaccessible_profile_ids:?}",+ ),+ },+ ))+ })?;}- Ok(Self::List(pi_list_params))- } else {- Ok(payment_intent_constraints)+ (_, None) => {}}+ Ok(payment_intent_constraints)}}diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rsindex f4836a12fe..d1cb551a35 100644--- a/crates/openapi/src/routes/payments.rs+++ b/crates/openapi/src/routes/payments.rs@@ -840,6 +840,8 @@ pub fn payments_update() {}/// - `succeeded`: If authorization is successful and `capture_method` is `automatic`./// - `requires_capture`: If authorization is successful and `capture_method` is `manual`./// - `failed`: If authorization fails.+/// Profile-restricted requests are authorized against the stored payment before payment-method+/// prefetch, retry records, address updates, or other confirmation side effects.#[utoipa::path(post,path = "/payments/{payment_id}/confirm",@@ -902,6 +904,9 @@ pub fn payments_confirm() {}/// The `amount_to_capture` can be specified in the request body; it must be less than or equal to the payment's `amount_capturable`. If omitted, the full capturable amount is captured.////// A payment must be in a capturable state (e.g., `requires_capture`). Attempting to capture an already `succeeded` (and fully captured) payment or one in an invalid state will lead to an error.+/// When authentication restricts access to a profile, the payment must belong to that profile.+/// This authorization is checked before creating a capture record, including for multiple captures.+/// Payments outside the authenticated merchant/profile scope are treated as not found.///#[utoipa::path(post,@@ -933,7 +938,8 @@ pub fn payments_confirm() {}),responses((status = 200, description = "Payment captured", body = PaymentsResponse),- (status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)+ (status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi),+ (status = 404, description = "Payment not found in the authenticated merchant/profile scope", body = GenericErrorResponseOpenApi)),tag = "Payments",operation_id = "Capture a Payment",@@ -983,6 +989,8 @@ pub fn payments_connector_session() {}/// Payments - Cancel////// A Payment could can be cancelled when it is in one of these statuses: `requires_payment_method`, `requires_capture`, `requires_confirmation`, `requires_customer_action`.+/// Profile-restricted authentication can cancel only payments in that profile.+/// Payments outside the authenticated merchant/profile scope are treated as not found before cancellation side effects.#[utoipa::path(post,path = "/payments/{payment_id}/cancel",@@ -1013,7 +1021,8 @@ pub fn payments_connector_session() {}),responses((status = 200, description = "Payment canceled"),- (status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)+ (status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi),+ (status = 404, description = "Payment not found in the authenticated merchant/profile scope", body = GenericErrorResponseOpenApi)),tag = "Payments",operation_id = "Cancel a Payment",diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex a15e547045..89550d5a07 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -68,6 +68,7 @@ use crate::{consts, types::payment_methods as pm_types};#[derive(Default)]pub struct PaymentMethodFetchData {pub payment_intent: Option<storage::PaymentIntent>,+ pub business_profile: Option<domain::Profile>,pub payment_method_info: Option<domain::PaymentMethod>,pub payment_method_with_raw_data: Option<PaymentMethodWithRawData>,pub token_data: Option<storage::PaymentTokenData>,@@ -78,6 +79,7 @@ impl PaymentMethodFetchData {pub fn from_modular(payment_method_with_raw_data: PaymentMethodWithRawData) -> Self {Self {payment_intent: None,+ business_profile: None,payment_method_info: Some(payment_method_with_raw_data.payment_method.clone()),payment_method_with_raw_data: Some(payment_method_with_raw_data),token_data: None,@@ -90,6 +92,7 @@ impl PaymentMethodFetchData {) -> Self {Self {payment_intent: None,+ business_profile: None,payment_method_info: Some(payment_method_info),payment_method_with_raw_data: None,token_data,diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 24503d67e5..eb2899b109 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -835,7 +835,13 @@ wherelet feature_config = core_utils::get_feature_config(state, platform, dimensions).await;let payment_method_fetch_data = operation.to_domain()?- .fetch_payment_method(state, &req, platform, &feature_config)+ .fetch_payment_method(+ state,+ &req,+ platform,+ &feature_config,+ profile_id_from_auth_layer.as_ref(),+ ).await?;tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));@@ -859,6 +865,7 @@ wherepayment_method_fetch_data,dimensions,payment_pre_fetched_info,+ profile_id_from_auth_layer.as_ref(),).await?;@@ -1839,6 +1846,7 @@ whereoperations::PaymentMethodFetchData::default(),dimensions,None,+ profile_id_from_auth_layer.as_ref(),).await?;let dimensions = dimensions.with_profile_id(business_profile.get_id().clone());@@ -3327,7 +3335,13 @@ wherelet payment_method_info = operation.to_domain()?- .fetch_payment_method(state, &req, &platform, &feature_config)+ .fetch_payment_method(+ state,+ &req,+ &platform,+ &feature_config,+ profile_id_from_auth_layer.as_ref(),+ ).await?;let operations::GetTrackerResponse {@@ -3347,6 +3361,7 @@ wherepayment_method_info,&dimensions,None,+ profile_id_from_auth_layer.as_ref(),)).await?;let dimensions = dimensions.with_profile_id(business_profile.get_id().clone());@@ -5200,6 +5215,7 @@ pub trait PaymentRedirectFlow: Sync {&platform.get_processor().get_processor_merchant_id(),platform.get_processor().get_key_store(),platform.get_processor().get_storage_scheme(),+ None,).await?;// All redirect URLs name the payment connector, including the external@@ -5835,6 +5851,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {&platform.get_processor().get_processor_merchant_id(),platform.get_processor().get_key_store(),platform.get_processor().get_storage_scheme(),+ None,).await?}diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex cb7297d830..c94bb05c50 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -132,6 +132,60 @@ use crate::{core::admin as core_admin, headers, types::ConnectorAuthType};#[cfg(feature = "v1")]use crate::{core::utils::create_encrypted_data, types::storage::CustomerUpdate::Update};+/// Use a profile-scoped lookup when authentication supplies a profile, otherwise retain merchant scope.+#[cfg(feature = "v1")]+pub async fn find_payment_intent(+ db: &dyn StorageInterface,+ payment_id: &id_type::PaymentId,+ processor_merchant_id: &domain::ProcessorMerchantId,+ key_store: &domain::ProcessorKeyStore,+ storage_scheme: domain::ProcessorStorageScheme,+ profile_id_from_auth_layer: Option<&id_type::ProfileId>,+) -> CustomResult<PaymentIntent, errors::StorageError> {+ match profile_id_from_auth_layer {+ Some(profile_id) => {+ db.find_payment_intent_by_payment_id_processor_merchant_id_profile_id(+ payment_id,+ processor_merchant_id,+ profile_id,+ key_store,+ storage_scheme,+ )+ .await+ }+ None => {+ db.find_payment_intent_by_payment_id_processor_merchant_id(+ payment_id,+ processor_merchant_id,+ key_store,+ storage_scheme,+ )+ .await+ }+ }+}++#[cfg(feature = "v1")]+pub(super) fn validate_payment_profile(+ authenticated_profile_id: Option<&id_type::ProfileId>,+ payment_profile_id: Option<&id_type::ProfileId>,+) -> RouterResult<()> {+ match (authenticated_profile_id, payment_profile_id) {+ (Some(authenticated), Some(payment)) => fp_utils::when(authenticated != payment, || {+ Err(errors::ApiErrorResponse::PreconditionFailed {+ message: "Profile id authentication failed. Please use the correct JWT token"+ .to_string(),+ }+ .into())+ }),+ (Some(_), None) => Err(errors::ApiErrorResponse::PreconditionFailed {+ message: "Couldn't find profile_id in record for authentication".to_string(),+ }+ .into()),+ (None, _) => Ok(()),+ }+}+#[instrument(skip_all)]#[allow(clippy::too_many_arguments)]pub async fn create_or_update_address_for_payment_by_request(diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rsindex a7fbcdccf0..07c48ee038 100644--- a/crates/router/src/core/payments/operations.rs+++ b/crates/router/src/core/payments/operations.rs@@ -375,6 +375,7 @@ pub struct GetTrackerResponse<'a, F: Clone, R, D> {/// This trait is used to fetch / create all the tracker related information for a payment/// This functions returns the session data that is used by subsequent functions+/// The authenticated profile is available to authorize stored payments before tracker side effects.#[async_trait]pub trait GetTracker<F: Clone, D, R>: Send {#[cfg(feature = "v1")]@@ -391,6 +392,7 @@ pub trait GetTracker<F: Clone, D, R>: Send {payment_method_fetch_data: PaymentMethodFetchData,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,payment_pre_fetched_info: Option<PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<GetTrackerResponse<'a, F, R, D>>;#[cfg(feature = "v2")]@@ -504,6 +506,7 @@ pub trait Domain<F: Clone, R, D>: Send + Sync {_request: &R,_platform: &domain::Platform,_feature_config: &core_utils::FeatureConfig,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<PaymentMethodFetchData> {Ok(PaymentMethodFetchData::default())}diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rsindex b478ae0d75..da7e6c2059 100644--- a/crates/router/src/core/payments/operations/payment_approve.rs+++ b/crates/router/src/core/payments/operations/payment_approve.rs@@ -47,6 +47,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR_payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, PaymentData<F>>,> {diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rsindex f343b3386a..b47fef6e47 100644--- a/crates/router/src/core/payments/operations/payment_cancel.rs+++ b/crates/router/src/core/payments/operations/payment_cancel.rs@@ -50,6 +50,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRepayment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, PaymentData<F>>,> {@@ -61,15 +62,16 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe.get_payment_intent_id().change_context(errors::ApiErrorResponse::PaymentNotFound)?;- let payment_intent = db- .find_payment_intent_by_payment_id_processor_merchant_id(- &payment_id,- &processor_merchant_id,- platform.get_processor().get_key_store(),- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ let payment_intent = helpers::find_payment_intent(+ db,+ &payment_id,+ &processor_merchant_id,+ platform.get_processor().get_key_store(),+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;helpers::validate_payment_status_against_not_allowed_statuses(payment_intent.status,diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rsindex 60b98aa324..9d050fdc5b 100644--- a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs+++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs@@ -48,6 +48,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelPopayment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture_sync.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture_sync.rsindex de8d8643a2..84c3773da1 100644--- a/crates/router/src/core/payments/operations/payment_cancel_post_capture_sync.rs+++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture_sync.rs@@ -48,6 +48,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, id_type::PaymentId>_payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, id_type::PaymentId, PaymentData<F>>>{let db = &*state.store;diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rsindex 0a62221e20..1bfe42f506 100644--- a/crates/router/src/core/payments/operations/payment_capture.rs+++ b/crates/router/src/core/payments/operations/payment_capture.rs@@ -53,6 +53,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymenpayment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a,@@ -71,15 +72,16 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen.get_payment_intent_id().change_context(errors::ApiErrorResponse::PaymentNotFound)?;- payment_intent = db- .find_payment_intent_by_payment_id_processor_merchant_id(- &payment_id,- &processor_merchant_id,- platform.get_processor().get_key_store(),- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ payment_intent = helpers::find_payment_intent(+ db,+ &payment_id,+ &processor_merchant_id,+ platform.get_processor().get_key_store(),+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;payment_attempt = db.find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(@@ -406,6 +408,13 @@ impl<F: Send + Clone + Sync>request: &api::PaymentsCaptureRequest,processor: &'a domain::Processor,) -> RouterResult<(PaymentCaptureOperation<'b, F>, operations::ValidateResult)> {+ let request_merchant_id = request.merchant_id.as_ref();+ helpers::validate_merchant_id(processor.get_account().get_id(), request_merchant_id)+ .change_context(errors::ApiErrorResponse::InvalidDataFormat {+ field_name: "merchant_id".into(),+ expected_format: "merchant_id from merchant account".to_string(),+ })?;+Ok((Box::new(self),operations::ValidateResult {diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rsindex d8c959d576..dba20fb1e1 100644--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs@@ -56,6 +56,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>{let operations::PaymentMethodFetchData {@@ -78,16 +79,23 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.change_context(errors::ApiErrorResponse::PaymentNotFound)?;payment_intent = match prefetched_payment_intent.or(pre_fetched_intent) {- Some(payment_intent) => payment_intent,- None => db- .find_payment_intent_by_payment_id_processor_merchant_id(- &payment_id,- &processor_merchant_id,- platform.get_processor().get_key_store(),- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,+ Some(payment_intent) => {+ helpers::validate_payment_profile(+ profile_id_from_auth_layer,+ payment_intent.profile_id.as_ref(),+ )?;+ payment_intent+ }+ None => helpers::find_payment_intent(+ db,+ &payment_id,+ &processor_merchant_id,+ platform.get_processor().get_key_store(),+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,};// TODO (#7195): Add platform merchant account validation once client_secret auth is solved@@ -463,6 +471,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forreq: &api::PaymentsRequest,platform: &domain::Platform,feature_config: &core_utils::FeatureConfig,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::PaymentMethodFetchData> {let payment_id = req.payment_id.as_ref().get_required_value("payment_id")?;let (payment_intent, payment_attempt) =@@ -472,6 +481,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for&platform.get_processor().get_processor_merchant_id(),platform.get_processor().get_key_store(),platform.get_processor().get_storage_scheme(),+ profile_id_from_auth_layer,)).await?;diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 3d2d7d3cfb..e19c5a339b 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -88,6 +88,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>payment_method_fetch_data: operations::PaymentMethodFetchData,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>{let operations::PaymentMethodFetchData {@@ -95,6 +96,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>payment_method_info: prefetched_payment_method_info,payment_method_with_raw_data,token_data: prefetched_token_data,+ ..} = payment_method_fetch_data;let (pre_fetched_intent, pre_fetched_attempt) = match payment_pre_fetched_info {Some(info) => (Some(info.payment_intent), Some(info.payment_attempt)),@@ -114,16 +116,23 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>// Parallel calls - level 0let mut payment_intent = match prefetched_payment_intent.or(pre_fetched_intent) {- Some(payment_intent) => payment_intent,- None => store- .find_payment_intent_by_payment_id_processor_merchant_id(- &payment_id,- &m_merchant_id,- platform.get_processor().get_key_store(),- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,+ Some(payment_intent) => {+ helpers::validate_payment_profile(+ profile_id_from_auth_layer,+ payment_intent.profile_id.as_ref(),+ )?;+ payment_intent+ }+ None => helpers::find_payment_intent(+ store,+ &payment_id,+ &m_merchant_id,+ platform.get_processor().get_key_store(),+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,};// TODO (#7195): Add platform merchant account validation once client_secret auth is solved@@ -1368,6 +1377,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forreq: &api::PaymentsRequest,platform: &domain::Platform,feature_config: &core_utils::FeatureConfig,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::PaymentMethodFetchData> {let payment_id = req.payment_id@@ -1375,16 +1385,16 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.get_required_value("payment_id")?.get_payment_intent_id().change_context(errors::ApiErrorResponse::PaymentNotFound)?;- let payment_intent = state- .store- .find_payment_intent_by_payment_id_processor_merchant_id(- &payment_id,- &platform.get_processor().get_processor_merchant_id(),- platform.get_processor().get_key_store(),- platform.get_processor().get_storage_scheme(),- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ let payment_intent = helpers::find_payment_intent(+ state.store.as_ref(),+ &payment_id,+ &platform.get_processor().get_processor_merchant_id(),+ platform.get_processor().get_key_store(),+ platform.get_processor().get_storage_scheme(),+ profile_id_from_auth_layer,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;let profile_id = payment_intent.profile_id.as_ref()@@ -1558,6 +1568,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for);operations::PaymentMethodFetchData {payment_intent: None,+ business_profile: None,payment_method_info: None,payment_method_with_raw_data: None,token_data,diff --git a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rsindex 1932f69261..1c50f45a0f 100644--- a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs@@ -188,6 +188,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>payment_method_fetch_data: PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsRequest, PaymentData<F>>> {let db = &*state.store;let payment_method_wrapper = payment_method_fetch_data.payment_method_with_raw_data;@@ -198,15 +199,25 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>.get_payment_intent_id().change_context(errors::ApiErrorResponse::PaymentNotFound)?;- let payment_intent = db- .find_payment_intent_by_payment_id_processor_merchant_id(+ let payment_intent = match payment_method_fetch_data.payment_intent {+ Some(payment_intent) => {+ helpers::validate_payment_profile(+ profile_id_from_auth_layer,+ payment_intent.profile_id.as_ref(),+ )?;+ payment_intent+ }+ None => helpers::find_payment_intent(+ db,&payment_id,&processor_merchant_id,platform.get_processor().get_key_store(),storage_scheme,+ profile_id_from_auth_layer,).await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,+ };if [Some(common_enums::PaymentSource::Webhook),@@ -790,7 +801,24 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>req: &PaymentsRequest,platform: &domain::Platform,feature_config: &core_utils::FeatureConfig,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<PaymentMethodFetchData> {+ let payment_id = req+ .payment_id+ .as_ref()+ .get_required_value("payment_id")?+ .get_payment_intent_id()+ .change_context(errors::ApiErrorResponse::PaymentNotFound)?;+ let payment_intent = helpers::find_payment_intent(+ state.store.as_ref(),+ &payment_id,+ &platform.get_processor().get_processor_merchant_id(),+ platform.get_processor().get_key_store(),+ platform.get_processor().get_storage_scheme(),+ profile_id_from_auth_layer,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;// Only the saved-card token flow (`VaultCardTokenData`) needs an up-front fetch. The inline// `VaultDataCard` flow carries the card on the request and is parsed in `get_trackers`.let card_token = req@@ -810,7 +838,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>// A fetch is only needed for the saved-card token flow, and only when the org is eligible// for the modular PM service. Every other case has nothing to fetch up front.- let fetch_data = match card_token {+ let mut fetch_data = match card_token {Some(card_token) if feature_config.is_payment_method_modular_allowed => {// 1. Resolve the payment_token to the actual stored payment_method_id via Redis.// This uses the same key construction as the regular Confirm flow's@@ -837,12 +865,11 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>// 2. Retrieve the external vault tokens for that payment method from the modular PM// service.- let profile_id = platform- .get_processor()- .get_account()- .get_default_profile()- .clone()+ let profile_id = payment_intent+ .profile_id+ .as_ref().get_required_value("profile_id")+ .change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("profile_id is required to fetch external vault tokens from the modular service",)?;@@ -851,7 +878,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>pm_transformers::fetch_payment_method_from_modular_service(state,platform,- &profile_id,+ profile_id,&payment_method_id,Some(card_token),// External vault proxy cards are not in the internal vault; requesting raw@@ -876,6 +903,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>// Not a token flow — nothing to fetch up front.None => PaymentMethodFetchData::default(),};+ fetch_data.payment_intent = Some(payment_intent);Ok(fetch_data)}diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex 3d0ef0684a..64aac805df 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -83,9 +83,11 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>payment_method_fetch_data: operations::PaymentMethodFetchData,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>{let operations::PaymentMethodFetchData {+ business_profile: prefetched_business_profile,payment_method_info: prefetched_payment_method_info,payment_method_with_raw_data,..@@ -106,14 +108,23 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>// If profile id is not passed, get it from the business_country and business_label.// The lookup is scoped to the merchant, so this also validates that the profile belongs to it.- let business_profile = core_utils::get_profile_from_business_details(- request.business_country,- request.business_label.as_ref(),- platform.get_processor(),- request.profile_id.as_ref(),- &*state.store,- )- .await?;+ let business_profile = match prefetched_business_profile {+ Some(business_profile) => business_profile,+ None => {+ core_utils::get_profile_from_business_details(+ request.business_country,+ request.business_label.as_ref(),+ platform.get_processor(),+ request.profile_id.as_ref(),+ &*state.store,+ )+ .await?+ }+ };+ helpers::validate_payment_profile(+ profile_id_from_auth_layer,+ Some(business_profile.get_id()),+ )?;let profile_id = business_profile.get_id().to_owned();let customer_acceptance = request.customer_acceptance.clone();@@ -935,8 +946,21 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forreq: &api::PaymentsRequest,platform: &domain::Platform,feature_config: &core_utils::FeatureConfig,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::PaymentMethodFetchData> {- let payment_method_fetch_data = if feature_config.is_payment_method_modular_allowed {+ let business_profile = core_utils::get_profile_from_business_details(+ req.business_country,+ req.business_label.as_ref(),+ platform.get_processor(),+ req.profile_id.as_ref(),+ &*state.store,+ )+ .await?;+ helpers::validate_payment_profile(+ profile_id_from_auth_layer,+ Some(business_profile.get_id()),+ )?;+ let mut payment_method_fetch_data = if feature_config.is_payment_method_modular_allowed {logger::debug!("PM Modular Service branch selected for payment method fetch");utils::when(req.off_session == Some(true) && req.recurring_details.is_none(),@@ -955,6 +979,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forstate,req,platform,+ business_profile.get_id(),payment_method_ref,).await?;@@ -1002,6 +1027,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forstate,req,platform,+ business_profile.get_id(),&payment_method_id,).await?;@@ -1015,6 +1041,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> foroperations::PaymentMethodFetchData::default()}};+ payment_method_fetch_data.business_profile = Some(business_profile);Ok(payment_method_fetch_data)}@@ -1346,22 +1373,13 @@ impl PaymentCreate {state: &SessionState,req: &api::PaymentsRequest,platform: &domain::Platform,+ profile_id: &common_utils::id_type::ProfileId,payment_method_ref: &str,) -> RouterResult<PaymentMethodWithRawData> {- let profile_id = req- .profile_id- .clone()- .or(platform- .get_processor()- .get_account()- .get_default_profile()- .clone())- .get_required_value("profile_id")?;-let pm_info = pm_transformers::fetch_payment_method_from_modular_service(state,platform,- &profile_id,+ profile_id,payment_method_ref,None, // CVC token data is not passed in create apitrue, // fetch raw card detail from the internal vaultdiff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rsindex f255939d94..2c6c0cde3e 100644--- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs+++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs@@ -49,6 +49,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess_payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/operations/payment_recurrence.rs b/crates/router/src/core/payments/operations/payment_recurrence.rsindex abfeb3a67a..1a58683206 100644--- a/crates/router/src/core/payments/operations/payment_recurrence.rs+++ b/crates/router/src/core/payments/operations/payment_recurrence.rs@@ -54,6 +54,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>payment_method_fetch_data: operations::PaymentMethodFetchData,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>{let operations::PaymentMethodFetchData {@@ -72,15 +73,16 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>let store = &*state.store;let m_merchant_id = processor_merchant_id.clone();- let payment_intent = store- .find_payment_intent_by_payment_id_processor_merchant_id(- &payment_id,- &m_merchant_id,- platform.get_processor().get_key_store(),- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ let payment_intent = helpers::find_payment_intent(+ store,+ &payment_id,+ &m_merchant_id,+ platform.get_processor().get_key_store(),+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;helpers::validate_payment_status_against_allowed_statuses(payment_intent.status,diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rsindex 5f0261b400..d48b719e0a 100644--- a/crates/router/src/core/payments/operations/payment_reject.rs+++ b/crates/router/src/core/payments/operations/payment_reject.rs@@ -46,6 +46,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest_payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>>{let db = &*state.store;diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rsindex a2eac6001c..108daf9cca 100644--- a/crates/router/src/core/payments/operations/payment_session.rs+++ b/crates/router/src/core/payments/operations/payment_session.rs@@ -49,6 +49,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR_payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsSessionRequest, PaymentData<F>>,> {@@ -60,15 +61,16 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionRlet processor_merchant_id = platform.get_processor().get_processor_merchant_id();let storage_scheme = platform.get_processor().get_storage_scheme();- let mut payment_intent = db- .find_payment_intent_by_payment_id_processor_merchant_id(- &payment_id,- &processor_merchant_id,- platform.get_processor().get_key_store(),- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ let mut payment_intent = helpers::find_payment_intent(+ db,+ &payment_id,+ &processor_merchant_id,+ platform.get_processor().get_key_store(),+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;// TODO (#7195): Add platform merchant account validation once publishable key auth is solveddiff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rsindex 454521d92c..2b2e20f72f 100644--- a/crates/router/src/core/payments/operations/payment_start.rs+++ b/crates/router/src/core/payments/operations/payment_start.rs@@ -49,6 +49,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq_payment_method_fetch_data: operations::PaymentMethodFetchData,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsStartRequest, PaymentData<F>>,> {diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rsindex f52e6846ee..742c68e80d 100644--- a/crates/router/src/core/payments/operations/payment_status.rs+++ b/crates/router/src/core/payments/operations/payment_status.rs@@ -240,6 +240,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieve_payment_method_fetch_data: operations::PaymentMethodFetchData,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>,> {@@ -252,6 +253,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveplatform.get_processor().get_storage_scheme(),dimensions,payment_pre_fetched_info,+ profile_id_from_auth_layer,)).await}@@ -291,15 +293,22 @@ async fn get_tracker_for_sync<storage_scheme: domain::ProcessorStorageScheme,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>>{let (payment_intent, mut payment_attempt, currency, amount);(payment_intent, payment_attempt) = match payment_pre_fetched_info {- Some(pre_fetched_info) => (- pre_fetched_info.payment_intent,- pre_fetched_info.payment_attempt,- ),+ Some(pre_fetched_info) => {+ helpers::validate_payment_profile(+ profile_id_from_auth_layer,+ pre_fetched_info.payment_intent.profile_id.as_ref(),+ )?;+ (+ pre_fetched_info.payment_intent,+ pre_fetched_info.payment_attempt,+ )+ }None => {get_payment_intent_payment_attempt(state,@@ -307,6 +316,7 @@ async fn get_tracker_for_sync<&platform.get_processor().get_processor_merchant_id(),platform.get_processor().get_key_store(),storage_scheme,+ profile_id_from_auth_layer,).await?}@@ -712,20 +722,22 @@ pub async fn get_payment_intent_payment_attempt(processor_merchant_id: &domain::ProcessorMerchantId,key_store: &domain::ProcessorKeyStore,storage_scheme: domain::ProcessorStorageScheme,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> {let db = &*state.store;let get_pi_pa = || async {let (pi, pa);match payment_id {api_models::payments::PaymentIdType::PaymentIntentId(ref id) => {- pi = db- .find_payment_intent_by_payment_id_processor_merchant_id(- id,- processor_merchant_id,- key_store,- storage_scheme,- )- .await?;+ pi = helpers::find_payment_intent(+ db,+ id,+ processor_merchant_id,+ key_store,+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await?;pa = db.find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(&pi.payment_id,@@ -745,14 +757,15 @@ pub async fn get_payment_intent_payment_attempt(key_store,).await?;- pi = db- .find_payment_intent_by_payment_id_processor_merchant_id(- &pa.payment_id,- processor_merchant_id,- key_store,- storage_scheme,- )- .await?;+ pi = helpers::find_payment_intent(+ db,+ &pa.payment_id,+ processor_merchant_id,+ key_store,+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await?;}api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => {pa = db@@ -763,14 +776,15 @@ pub async fn get_payment_intent_payment_attempt(key_store,).await?;- pi = db- .find_payment_intent_by_payment_id_processor_merchant_id(- &pa.payment_id,- processor_merchant_id,- key_store,- storage_scheme,- )- .await?;+ pi = helpers::find_payment_intent(+ db,+ &pa.payment_id,+ processor_merchant_id,+ key_store,+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await?;}}error_stack::Result::<_, errors::StorageError>::Ok((pi, pa))diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rsindex 83d5daa3cf..ae3ff8b5a7 100644--- a/crates/router/src/core/payments/operations/payment_update.rs+++ b/crates/router/src/core/payments/operations/payment_update.rs@@ -66,6 +66,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>_payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>{let (mut payment_intent, mut payment_attempt, currency): (_, _, storage_enums::Currency);@@ -83,15 +84,16 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>auth_flow,).await?;- payment_intent = db- .find_payment_intent_by_payment_id_processor_merchant_id(- &payment_id,- &processor_merchant_id,- platform.get_processor().get_key_store(),- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;+ payment_intent = helpers::find_payment_intent(+ db,+ &payment_id,+ &processor_merchant_id,+ platform.get_processor().get_key_store(),+ storage_scheme,+ profile_id_from_auth_layer,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;// TODO (#7195): Add platform merchant account validation once publishable key auth is solveddiff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rsindex 4e39056446..f87713a4a6 100644--- a/crates/router/src/core/payments/operations/payment_update_metadata.rs+++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs@@ -49,6 +49,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMe_payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsUpdateMetadataRequest, PaymentData<F>>,> {diff --git a/crates/router/src/core/payments/operations/payments_extend_authorization.rs b/crates/router/src/core/payments/operations/payments_extend_authorization.rsindex 68e382cb2b..42dcf56558 100644--- a/crates/router/src/core/payments/operations/payments_extend_authorization.rs+++ b/crates/router/src/core/payments/operations/payments_extend_authorization.rs@@ -48,6 +48,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsExtendAu_payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rsindex 47db25ff60..992c8af20f 100644--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs@@ -55,6 +55,7 @@ impl<F: Send + Clone + Sync>payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rsindex 0fa60aca83..3ac83176da 100644--- a/crates/router/src/core/payments/operations/tax_calculation.rs+++ b/crates/router/src/core/payments/operations/tax_calculation.rs@@ -54,6 +54,7 @@ impl<F: Send + Clone + Sync>_payment_method_fetch_data: operations::PaymentMethodFetchData,_dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,_payment_pre_fetched_info: Option<operations::PaymentPreFetchedInformation>,+ _profile_id_from_auth_layer: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<operations::GetTrackerResponse<'a,diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 173a3f47cf..3ceb6d294a 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -2191,6 +2191,26 @@ impl PaymentIntentInterface for KafkaStore {.await}+ #[cfg(feature = "v1")]+ async fn find_payment_intent_by_payment_id_processor_merchant_id_profile_id(+ &self,+ payment_id: &id_type::PaymentId,+ processor_merchant_id: &ProcessorMerchantId,+ profile_id: &id_type::ProfileId,+ merchant_key_store: &ProcessorKeyStore,+ storage_scheme: ProcessorStorageScheme,+ ) -> CustomResult<storage::PaymentIntent, errors::StorageError> {+ self.diesel_store+ .find_payment_intent_by_payment_id_processor_merchant_id_profile_id(+ payment_id,+ processor_merchant_id,+ profile_id,+ merchant_key_store,+ storage_scheme,+ )+ .await+ }+#[cfg(feature = "v2")]async fn find_payment_intent_by_id(&self,diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex 35931ad9ee..fdc38e2ce3 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -1994,7 +1994,8 @@ pub async fn payments_cancel(&header_payload,crate::core::payment_methods::transformers::PaymentMethodFetchData::default(),&preliminary_dimensions,- None+ None,+ auth.profile.as_ref().map(|profile| profile.get_id()),).await?;diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rsindex c3e4f1fdd0..af0d392565 100644--- a/crates/storage_impl/src/mock_db/payment_intent.rs+++ b/crates/storage_impl/src/mock_db/payment_intent.rs@@ -227,6 +227,30 @@ impl PaymentIntentInterface for MockDb {.unwrap())}+ #[cfg(feature = "v1")]+ async fn find_payment_intent_by_payment_id_processor_merchant_id_profile_id(+ &self,+ payment_id: &common_utils::id_type::PaymentId,+ processor_merchant_id: &ProcessorMerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ _key_store: &ProcessorKeyStore,+ _storage_scheme: ProcessorStorageScheme,+ ) -> CustomResult<PaymentIntent, StorageError> {+ self.payment_intents+ .lock()+ .await+ .iter()+ .find(|payment_intent| {+ payment_intent.get_id() == payment_id+ && payment_intent+ .processor_merchant_id+ .eq(processor_merchant_id)+ && payment_intent.profile_id.as_ref() == Some(profile_id)+ })+ .cloned()+ .ok_or_else(|| StorageError::ValueNotFound("PaymentIntent not found".to_owned()).into())+ }+#[cfg(feature = "v2")]async fn find_payment_intent_by_id(&self,diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rsindex f25b6c065d..312f3826c0 100644--- a/crates/storage_impl/src/payments/payment_intent.rs+++ b/crates/storage_impl/src/payments/payment_intent.rs@@ -403,6 +403,42 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {.await}+ #[cfg(feature = "v1")]+ #[instrument(skip_all)]+ async fn find_payment_intent_by_payment_id_processor_merchant_id_profile_id(+ &self,+ payment_id: &common_utils::id_type::PaymentId,+ processor_merchant_id: &ProcessorMerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ merchant_key_store: &ProcessorKeyStore,+ storage_scheme: ProcessorStorageScheme,+ ) -> error_stack::Result<PaymentIntent, StorageError> {+ let conn = pg_connection_read(self).await?;+ let payment_intent: PaymentIntent = Box::pin(self.find_resource_by_id_old(+ merchant_key_store,+ storage_scheme.inner(),+ DieselPaymentIntent::find_by_payment_id_processor_merchant_id_profile_id(+ &conn,+ payment_id,+ processor_merchant_id,+ profile_id,+ ),+ FindResourceBy::Id(+ payment_id.get_hash_key_for_kv_store(),+ PartitionKey::MerchantIdPaymentId {+ merchant_id: processor_merchant_id,+ payment_id,+ },+ ),+ ))+ .await?;+ if payment_intent.profile_id.as_ref() == Some(profile_id) {+ Ok(payment_intent)+ } else {+ Err(StorageError::ValueNotFound("PaymentIntent not found".to_owned()).into())+ }+ }+#[cfg(feature = "v2")]#[instrument(skip_all)]async fn find_payment_intent_by_id(@@ -819,6 +855,42 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {.await}+ #[cfg(feature = "v1")]+ #[instrument(skip_all)]+ async fn find_payment_intent_by_payment_id_processor_merchant_id_profile_id(+ &self,+ payment_id: &common_utils::id_type::PaymentId,+ processor_merchant_id: &ProcessorMerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ merchant_key_store: &ProcessorKeyStore,+ _storage_scheme: ProcessorStorageScheme,+ ) -> error_stack::Result<PaymentIntent, StorageError> {+ let conn = pg_connection_read(self).await?;+ DieselPaymentIntent::find_by_payment_id_processor_merchant_id_profile_id(+ &conn,+ payment_id,+ processor_merchant_id,+ profile_id,+ )+ .await+ .map_err(|error| {+ let context = diesel_error_to_data_error(*error.current_context());+ error.change_context(context)+ })+ .async_and_then(|payment_intent| async {+ PaymentIntent::convert_back(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ payment_intent,+ merchant_key_store.key.get_inner(),+ merchant_key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)+ })+ .await+ }+#[cfg(feature = "v2")]#[instrument(skip_all)]async fn find_payment_intent_by_id(@@ -903,8 +975,14 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {);match filters {- PaymentIntentFetchConstraints::Single { payment_intent_id } => {+ PaymentIntentFetchConstraints::Single {+ payment_intent_id,+ profile_id,+ } => {query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()));+ if let Some(profile_ids) = profile_id {+ query = query.filter(pi_dsl::profile_id.eq_any(profile_ids.clone()));+ }}PaymentIntentFetchConstraints::List(params) => {if let Some(customer_id) = ¶ms.customer_id {@@ -1023,8 +1101,15 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {);query = match filters {- PaymentIntentFetchConstraints::Single { payment_intent_id } => {- query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))+ PaymentIntentFetchConstraints::Single {+ payment_intent_id,+ profile_id,+ } => {+ query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()));+ if let Some(profile_ids) = profile_id {+ query = query.filter(pi_dsl::profile_id.eq_any(profile_ids.clone()));+ }+ query}PaymentIntentFetchConstraints::List(params) => {query = match params.order {@@ -1173,8 +1258,15 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {);query = match filters {- PaymentIntentFetchConstraints::Single { payment_intent_id } => {- query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))+ PaymentIntentFetchConstraints::Single {+ payment_intent_id,+ profile_id,+ } => {+ query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()));+ if let Some(profile_ids) = profile_id {+ query = query.filter(pi_dsl::profile_id.eq_any(profile_ids.clone()));+ }+ query}PaymentIntentFetchConstraints::List(params) => {if let Some(processor_merchant_id) = ¶ms.processor_merchant_id {@@ -1345,8 +1437,15 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {);query = match constraints {- PaymentIntentFetchConstraints::Single { payment_intent_id } => {- query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))+ PaymentIntentFetchConstraints::Single {+ payment_intent_id,+ profile_id,+ } => {+ query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()));+ if let Some(profile_ids) = profile_id {+ query = query.filter(pi_dsl::profile_id.eq_any(profile_ids.clone()));+ }+ query}PaymentIntentFetchConstraints::List(params) => {query = match params.order {@@ -1854,8 +1953,15 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {);query = match constraints {- PaymentIntentFetchConstraints::Single { payment_intent_id } => {- query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))+ PaymentIntentFetchConstraints::Single {+ payment_intent_id,+ profile_id,+ } => {+ query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()));+ if let Some(profile_ids) = profile_id {+ query = query.filter(pi_dsl::profile_id.eq_any(profile_ids.clone()));+ }+ query}PaymentIntentFetchConstraints::List(params) => {if let Some(customer_id) = ¶ms.customer_id {