Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(payment-methods): external vault configuration for platform merchants (#12708)
Apoorv Dixit27f28188a031
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex 0dfb934f28..da0e8ef20c 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -2718,6 +2718,28 @@ pub async fn create_connector(},)?;+ fp_utils::when(+ processor.get_account().merchant_account_type == MerchantAccountType::Connected+ && api_models::enums::VaultConnectors::try_from(req.connector_name).is_ok(),+ || {+ Err(errors::ApiErrorResponse::InvalidRequestData {+ message:+ "Vault connectors can only be configured by platform or standard merchants, not connected merchants"+ .to_string(),+ })+ },+ )?;++ fp_utils::when(+ processor.get_account().merchant_account_type == MerchantAccountType::Platform+ && api_models::enums::VaultConnectors::try_from(req.connector_name).is_err(),+ || {+ Err(errors::ApiErrorResponse::InvalidRequestData {+ message: "Platform merchants can only configure vault connectors".to_string(),+ })+ },+ )?;+let connector_metadata = ConnectorMetadata {connector_metadata: &req.metadata,};@@ -3860,13 +3882,67 @@ impl ProfileCreateBridge for api::ProfileCreate {}}-#[cfg(feature = "olap")]+#[cfg(all(feature = "olap", feature = "v1"))]+/// External vault can only be configured on the provider merchant in the Platform setup. Connected+/// merchants share the platform's vault pool and must not configure their own external vault.+fn validate_external_vault_config_for_merchant_account_type(+ merchant_account_type: MerchantAccountType,+ is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>,+ has_external_vault_connector_details: bool,+) -> RouterResult<()> {+ let is_external_vault_being_configured = matches!(+ is_external_vault_enabled,+ Some(common_enums::ExternalVaultEnabled::Enable)+ ) || has_external_vault_connector_details;+ fp_utils::when(+ is_external_vault_being_configured+ && merchant_account_type == MerchantAccountType::Connected,+ || {+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message:+ "External vault can only be configured for platform merchant, not for connected merchants"+ .to_string(),+ }))+ },+ )+}++#[cfg(all(feature = "olap", feature = "v2"))]+/// External vault can only be configured on the provider merchant in the Platform setup. Connected+/// merchants share the platform's vault pool and must not configure their own external vault.+fn validate_external_vault_config_for_merchant_account_type(+ merchant_account_type: MerchantAccountType,+ is_external_vault_enabled: Option<bool>,+ has_external_vault_connector_details: bool,+) -> RouterResult<()> {+ let is_external_vault_being_configured =+ is_external_vault_enabled == Some(true) || has_external_vault_connector_details;+ fp_utils::when(+ is_external_vault_being_configured+ && merchant_account_type == MerchantAccountType::Connected,+ || {+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message:+ "External vault can only be configured for platform merchant, not for connected merchants"+ .to_string(),+ }))+ },+ )+}+pub async fn create_profile(state: SessionState,request: api::ProfileCreate,processor: domain::Processor,) -> RouterResponse<api_models::admin::ProfileResponse> {let db = state.store.as_ref();++ validate_external_vault_config_for_merchant_account_type(+ processor.get_account().merchant_account_type,+ request.is_external_vault_enabled,+ request.external_vault_connector_details.is_some(),+ )?;+#[cfg(feature = "v1")]let business_profile = request.create_domain_model_from_request(&state, &processor)@@ -4395,6 +4471,17 @@ pub async fn update_profile(request: api::ProfileUpdate,) -> RouterResponse<api::ProfileResponse> {let db = state.store.as_ref();++ let merchant_account = db+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;+ validate_external_vault_config_for_merchant_account_type(+ merchant_account.merchant_account_type,+ request.is_external_vault_enabled,+ request.external_vault_connector_details.is_some(),+ )?;+let business_profile = db.find_business_profile_by_merchant_id_profile_id(&key_store, &merchant_id, profile_id).awaitdiff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rsindex b9b302e08d..cc332a2c8d 100644--- a/crates/router/src/core/customers.rs+++ b/crates/router/src/core/customers.rs@@ -792,9 +792,11 @@ impl CustomerDeleteBridge for id_type::GlobalCustomerId {{Ok(customer_payment_methods) => {for pm in customer_payment_methods.into_iter() {- delete_payment_method_by_record(db, state, platform, &profile, pm)- .await- .switch()?;+ Box::pin(delete_payment_method_by_record(+ db, state, platform, &profile, pm,+ ))+ .await+ .switch()?;}}Err(error) => {diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 48eb5e5258..bb91ddb27a 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -2993,10 +2993,13 @@ pub async fn create_payment_method_proxy_card_core(let key_manager_state = &(state).into();// A proxy card is, by definition, vaulted in an external vault, so the external vault- // connector must be configured on the profile. Fetch it from the profile and require it —- // otherwise the payment method would be persisted with a `None` external vault source.+ // connector must be configured on the resolved profile (the platform merchant's profile in+ // platform flows). Fetch it from the profile and require it — otherwise the payment method+ // would be persisted with a `None` external vault source.+ let external_vault_profile =+ payments_core::helpers::resolve_provider_profile(state, platform, profile).await?;let external_vault_source = Some(- profile+ external_vault_profile.external_vault_connector_details.clone().map(|details| details.vault_connector_id)@@ -4783,11 +4786,13 @@ pub async fn vault_payment_method(pm_types::AddVaultResponse,Option<id_type::MerchantConnectorAccountId>,)> {- let is_external_vault_enabled = profile.is_external_vault_enabled();+ let external_vault_profile =+ payments_core::helpers::resolve_provider_profile(state, platform, profile).await?;+ let is_external_vault_enabled = external_vault_profile.is_external_vault_enabled();match is_external_vault_enabled {true => {- let (external_vault_source, vault_token_selector) = profile+ let (external_vault_source, vault_token_selector) = external_vault_profile.external_vault_connector_details.clone().map(|connector_details| {@@ -4801,9 +4806,9 @@ pub async fn vault_payment_method(let merchant_connector_account =domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(- payments_core::helpers::get_merchant_connector_account_v2(+ payments_core::helpers::get_provider_mca_v2(state,- platform.get_processor(),+ platform.get_provider(),Some(&external_vault_source),).await@@ -5264,13 +5269,25 @@ pub async fn retrieve_payment_method(.attach_printable("Failed to retrieve cvc from redis").ok();- let raw_payment_method_data = raw_payment_method_fetch_access- .get_raw_payment_method_data(&state, &platform, &profile, &payment_method, storage_type)+ let raw_payment_method_data =+ Box::pin(raw_payment_method_fetch_access.get_raw_payment_method_data(+ &state,+ &platform,+ &profile,+ &payment_method,+ storage_type,+ )).await.attach_printable("Failed to get raw payment method data")?;- let raw_network_token_details = raw_payment_method_fetch_access- .get_raw_network_token_data(&state, &platform, &profile, &payment_method, storage_type)+ let raw_network_token_details =+ Box::pin(raw_payment_method_fetch_access.get_raw_network_token_data(+ &state,+ &platform,+ &profile,+ &payment_method,+ storage_type,+ )).await.inspect_err(|err| {logger::warn!(?err, "Failed to fetch raw network token details");@@ -5575,13 +5592,13 @@ impl RawPaymentMethodFetchAccess {logger::debug!("Skipping raw payment method fetch for wallet or bank redirect payment method");Ok(None)} else {- let vault_data = vault::retrieve_payment_method_data_from_storage(+ let vault_data = Box::pin(vault::retrieve_payment_method_data_from_storage(state,platform,profile,payment_method,storage_type,- )+ )).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to retrieve payment method from vault")?@@ -5636,17 +5653,18 @@ impl RawPaymentMethodFetchAccess {Some(domain::VaultId::generate(network_token_locker_id));network_token_payment_method.customer_id = Some(customer_id);- let network_token_vault_data = vault::retrieve_payment_method_data_from_storage(- state,- platform,- profile,- &network_token_payment_method,- storage_type,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to retrieve network token from vault")?- .data;+ let network_token_vault_data =+ Box::pin(vault::retrieve_payment_method_data_from_storage(+ state,+ platform,+ profile,+ &network_token_payment_method,+ storage_type,+ ))+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to retrieve network token from vault")?+ .data;let check_token_status_response =network_tokenization::do_status_check_for_network_token(state, payment_method)@@ -5905,7 +5923,14 @@ pub async fn delete_payment_method_core(.to_not_found_response(errors::ApiErrorResponse::InternalServerError).attach_printable("Customer not found for the payment method")?;- delete_payment_method_by_record(db, state, platform, profile, payment_method).await?;+ Box::pin(delete_payment_method_by_record(+ db,+ state,+ platform,+ profile,+ payment_method,+ ))+ .await?;let response = api::PaymentMethodDeleteResponse { id: pm_id };@@ -7173,16 +7198,17 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {return Ok((None, None));}- let pmd: domain::PaymentMethodVaultingData = vault::retrieve_payment_method_from_vault(- self.state,- self.platform,- self.profile,- &self.payment_method,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to retrieve payment method from vault")?- .data;+ let pmd: domain::PaymentMethodVaultingData =+ Box::pin(vault::retrieve_payment_method_from_vault(+ self.state,+ self.platform,+ self.profile,+ &self.payment_method,+ ))+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to retrieve payment method from vault")?+ .data;let vault_request_data = self.requestdiff --git a/crates/router/src/core/payment_methods/client.rs b/crates/router/src/core/payment_methods/client.rsindex 37d3ae373e..753b9c0393 100644--- a/crates/router/src/core/payment_methods/client.rs+++ b/crates/router/src/core/payment_methods/client.rs@@ -195,7 +195,7 @@ impl CustomerPaymentMethodsFetcher for ModularCustomerPaymentMethodsFetcher {.find_merchant_connector_account_by_merchant_id_and_disabled_list(&merchant_id,true,- platform.get_provider().get_key_store(),+ platform.get_processor().get_key_store(),).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rsindex e9dacfe48d..c98fcdbfbc 100644--- a/crates/router/src/core/payment_methods/vault.rs+++ b/crates/router/src/core/payment_methods/vault.rs@@ -2200,6 +2200,14 @@ pub async fn retrieve_payment_method_from_vault_external(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to get the connector data")?;+ access_token::create_access_token(+ state,+ &connector_data,+ merchant_account.get_id(),+ &mut old_router_data,+ )+ .await?;+let connector_integration: services::BoxedVaultConnectorIntegrationInterface<ExternalVaultRetrieveFlow,types::VaultRequestData,@@ -2297,11 +2305,16 @@ pub async fn retrieve_payment_method_from_vault_using_payment_token(.await.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;- let vault_data = retrieve_payment_method_from_vault(state, platform, profile, &payment_method)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to retrieve payment method from vault")?- .data;+ let vault_data = Box::pin(retrieve_payment_method_from_vault(+ state,+ platform,+ profile,+ &payment_method,+ ))+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to retrieve payment method from vault")?+ .data;Ok((payment_method, vault_data))}@@ -2469,7 +2482,10 @@ pub async fn retrieve_payment_method_data_from_storage() -> RouterResult<pm_types::VaultRetrieveResponse> {let mut payment_method_data = match storage_type {enums::StorageType::Persistent => {- retrieve_payment_method_from_vault(state, platform, profile, pm).await?+ Box::pin(retrieve_payment_method_from_vault(+ state, platform, profile, pm,+ ))+ .await?}enums::StorageType::Volatile => {retrieve_volatile_payment_method_from_redis(@@ -2557,7 +2573,9 @@ pub async fn retrieve_payment_method_from_vault(profile: &domain::Profile,pm: &domain::PaymentMethod,) -> RouterResult<pm_types::VaultRetrieveResponse> {- let is_external_vault_enabled = profile.is_external_vault_enabled();+ let external_vault_profile =+ payments_core::helpers::resolve_provider_profile(state, platform, profile).await?;+ let is_external_vault_enabled = external_vault_profile.is_external_vault_enabled();match is_external_vault_enabled {true => {@@ -2565,9 +2583,9 @@ pub async fn retrieve_payment_method_from_vault(let merchant_connector_account =domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(- payments_core::helpers::get_merchant_connector_account_v2(+ payments_core::helpers::get_provider_mca_v2(state,- platform.get_processor(),+ platform.get_provider(),external_vault_source,).await@@ -2730,7 +2748,9 @@ pub async fn delete_payment_method_data_from_vault(profile: &domain::Profile,pm: &domain::PaymentMethod,) -> RouterResult<pm_types::VaultDeleteResponse> {- let is_external_vault_enabled = profile.is_external_vault_enabled();+ let external_vault_profile =+ payments_core::helpers::resolve_provider_profile(state, platform, profile).await?;+ let is_external_vault_enabled = external_vault_profile.is_external_vault_enabled();let vault_id = pm.locker_id@@ -2748,9 +2768,9 @@ pub async fn delete_payment_method_data_from_vault(let merchant_connector_account =domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(- payments_core::helpers::get_merchant_connector_account_v2(+ payments_core::helpers::get_provider_mca_v2(state,- platform.get_processor(),+ platform.get_provider(),external_vault_source,).awaitdiff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 299b03dccf..13fe02536e 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2891,11 +2891,11 @@ pub async fn fetch_card_details_from_locker(} => {Box::pin(fetch_card_details_from_external_vault(state,- platform.get_processor().get_account().get_id(),+ platform.get_provider().get_account().get_id(),card_token_data,co_badged_card_data,payment_method_info,- platform.get_processor().get_key_store(),+ platform.get_provider().get_key_store(),external_vault_source,)).await@@ -2914,6 +2914,72 @@ pub async fn fetch_card_details_from_locker(}}+/// Resolve the provider (platform) merchant's business profile in a platform-connected flow.+///+/// In a platform-connected flow the payment runs under the connected (processor) merchant,+/// but provider-level configuration (such as external vault) lives on the provider merchant's+/// profile, so we resolve the provider merchant's single profile. For standard merchants+/// (provider == processor) the supplied payment profile is returned unchanged, keeping+/// standard flows untouched.+pub async fn resolve_provider_profile(+ state: &SessionState,+ platform: &domain::Platform,+ payment_profile: &domain::Profile,+) -> RouterResult<domain::Profile> {+ let provider = platform.get_provider();+ let processor = platform.get_processor();++ if provider.get_account().get_id() == processor.get_account().get_id() {+ Ok(payment_profile.clone())+ } else {+ #[cfg(feature = "v1")]+ {+ let profile_id = provider+ .get_account()+ .get_default_profile()+ .clone()+ .ok_or_else(|| {+ report!(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Provider merchant has no default profile configured")+ })?;++ state+ .store+ .find_business_profile_by_profile_id(provider.get_key_store(), &profile_id)+ .await+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })+ }+ #[cfg(feature = "v2")]+ {+ Err(+ report!(errors::ApiErrorResponse::InternalServerError).attach_printable(+ "Platform-connected provider profile resolution is not supported in v2",+ ),+ )+ }+ }+}++#[cfg(feature = "v2")]+pub async fn get_provider_mca_v2(+ state: &SessionState,+ provider: &domain::Provider,+ merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,+) -> RouterResult<domain::MerchantConnectorAccount> {+ let merchant_connector_id = merchant_connector_id+ .get_required_value("merchant_connector_id")+ .attach_printable("merchant_connector_id not provided")?;+ state+ .store+ .find_merchant_connector_account_by_id(merchant_connector_id, provider.get_key_store())+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: merchant_connector_id.get_string_repr().to_string(),+ })+}+#[cfg(feature = "v1")]pub async fn fetch_card_details_from_internal_locker(state: &SessionState,diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rsindex d4e7b59dbc..3ce89bddd1 100644--- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs@@ -561,17 +561,18 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConfSome(domain::payment_method_data::PaymentMethodData::CardToken(card_token)),None,) => {- let (payment_method, vault_data) =+ let (payment_method, vault_data) = Box::pin(payment_methods::vault::retrieve_payment_method_from_vault_using_payment_token(state,platform,business_profile,payment_token,&payment_data.payment_attempt.payment_method_type,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to retrieve payment method from vault")?;+ ),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to retrieve payment method from vault")?;let (card_cvc, card_holder_name) = {(diff --git a/crates/router/src/core/payments/session_operation.rs b/crates/router/src/core/payments/session_operation.rsindex e21eba130e..8595cbeb98 100644--- a/crates/router/src/core/payments/session_operation.rs+++ b/crates/router/src/core/payments/session_operation.rs@@ -166,7 +166,7 @@ where.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound).attach_printable("Failed while fetching/creating customer")?;- vault_session::populate_vault_session_details(+ Box::pin(vault_session::populate_vault_session_details(state,req_state.clone(),&customer,@@ -177,7 +177,7 @@ whereheader_payload.clone(),// V2 gates internally on `profile.is_vault_sdk_enabled()`; this flag is ignored here.false,- )+ )).await?;let connector = operationdiff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex 0d2fb1c06c..9e8379488e 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -98,13 +98,16 @@ async fn save_in_locker(domain::PaymentMethodResponse,Option<payment_methods::transformers::DataDuplicationCheck>,)> {- match &business_profile.external_vault_details {+ let external_vault_profile =+ helpers::resolve_provider_profile(state, platform, business_profile).await?;++ match &external_vault_profile.external_vault_details {domain::ExternalVaultDetails::ExternalVaultEnabled(external_vault_details) => {logger::info!("External vault is enabled, using vault_payment_method_external_v1");Box::pin(save_in_locker_external(state,- platform.get_processor(),+ platform.get_provider(),payment_method_request,card_detail,external_vault_details,@@ -433,7 +436,7 @@ where.async_map(|customer_details| {create_encrypted_data(&key_manager_state,- platform.get_processor().get_key_store(),+ platform.get_provider().get_key_store(),customer_details,common_utils::type_name!(diesel_models::payment_method::PaymentMethod),)@@ -445,7 +448,9 @@ wherelet mut payment_method_id = resp.payment_method_id.clone();let mut locker_id = None;- let (external_vault_details, vault_type) = match &business_profile.external_vault_details{+ let external_vault_profile =+ helpers::resolve_provider_profile(state, platform, business_profile).await?;+ let (external_vault_details, vault_type) = match &external_vault_profile.external_vault_details{hyperswitch_domain_models::business_profile::ExternalVaultDetails::ExternalVaultEnabled(external_vault_connector_details) => {(Some(external_vault_connector_details), Some(common_enums::VaultType::External))},@@ -1358,7 +1363,7 @@ pub async fn save_in_locker_internal(#[cfg(feature = "v1")]pub async fn save_in_locker_external(state: &SessionState,- processor: &domain::Processor,+ provider: &domain::Provider,payment_method_request: api::PaymentMethodCreate,card_detail: Option<api::CardDetail>,external_vault_connector_details: &ExternalVaultConnectorDetails,@@ -1384,9 +1389,9 @@ pub async fn save_in_locker_external(let merchant_connector_account_details = state.store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(- processor.get_account().get_id(),+ provider.get_account().get_id(),&external_vault_mca_id,- processor.get_key_store(),+ provider.get_key_store(),).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {@@ -1397,7 +1402,7 @@ pub async fn save_in_locker_external(let vault_response = Box::pin(vault_payment_method_external_v1(state,&payment_method_custom_vaulting_data,- processor.get_account(),+ provider.get_account(),merchant_connector_account_details,None,))@@ -1407,7 +1412,7 @@ pub async fn save_in_locker_external(let card_detail = CardDetailFromLocker::from(card);let pm_resp = domain::PaymentMethodResponse {- merchant_id: processor.get_account().get_id().to_owned(),+ merchant_id: provider.get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id,payment_method: payment_method_request.payment_method,@@ -1430,7 +1435,7 @@ pub async fn save_in_locker_external(//Similar implementation is done for save in locker internallet pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");let payment_method_response = domain::PaymentMethodResponse {- merchant_id: processor.get_account().get_id().to_owned(),+ merchant_id: provider.get_account().get_id().to_owned(),customer_id: Some(customer_id),payment_method_id: pm_id,payment_method: payment_method_request.payment_method,diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rsindex ecdbb5ae4f..9ddcdeaa8e 100644--- a/crates/router/src/core/payments/vault_session.rs+++ b/crates/router/src/core/payments/vault_session.rs@@ -30,7 +30,7 @@ use hyperswitch_masking::Mask;#[cfg(feature = "v2")]use crate::core::{errors::utils::ConnectorErrorExt,- payments::{customers, gateway::context as gateway_context, helpers},+ payments::{customers, gateway::context as gateway_context},utils as core_utils,};use crate::{@@ -38,6 +38,7 @@ use crate::{errors::{self, RouterResult},payments::{flows::{ConstructFlowSpecificData, Feature},+ helpers,operations::BoxedOperation,OperationSessionGetters, OperationSessionSetters,},@@ -79,7 +80,9 @@ wheredyn api::Connector:services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,{- let is_external_vault_sdk_enabled = profile.is_vault_sdk_enabled();+ let external_vault_profile =+ helpers::resolve_provider_profile(state, platform, profile).await?;+ let is_external_vault_sdk_enabled = external_vault_profile.is_vault_sdk_enabled();if is_external_vault_sdk_enabled {// Guest flow (no customer) uses volatile storage; a known customer uses persistent.@@ -104,7 +107,6 @@ where#[cfg(feature = "v1")]async fn call_internal_pm_session_create_for_vault(state: &SessionState,- platform: &domain::Platform,profile: &domain::Profile,customer_id: Option<&id_type::CustomerId>,) -> RouterResult<Option<api::VaultDetails>> {@@ -113,7 +115,9 @@ async fn call_internal_pm_session_create_for_vault(CreatePaymentMethodSession, CreatePaymentMethodSessionV1Request, PaymentMethodClient,};- let processor_merchant_id = platform.get_processor().get_account().get_id();+ // The merchant that owns the supplied profile; in platform flows this is the platform+ // (provider) merchant whose profile carries the external vault configuration.+ let merchant_id = &profile.merchant_id;let profile_id = profile.get_id();let internal_api_key = &state.conf@@ -127,10 +131,7 @@ async fn call_internal_pm_session_create_for_vault());headers.insert((crate::headers::X_MERCHANT_ID.to_string(),- processor_merchant_id- .get_string_repr()- .to_string()- .into_masked(),+ merchant_id.get_string_repr().to_string().into_masked(),));headers.insert((crate::headers::X_INTERNAL_API_KEY.to_string(),@@ -215,10 +216,15 @@ where// for it (not just when an external vault is configured). When no external vault is set up, the// PM service returns the internal Hyperswitch vault SDK authorization, which is the SaaS default.if is_modular_service_enabled {+ let external_vault_profile =+ helpers::resolve_provider_profile(state, platform, profile).await?;let customer_id = customer.as_ref().map(|c| c.get_id());+ // Use the resolved external vault profile (the platform merchant's profile in platform+ // flows) so the PM service operates under the merchant that actually holds the external+ // vault configuration. For standard merchants this is the payment profile itself.let vault_details =- call_internal_pm_session_create_for_vault(state, platform, profile, customer_id)+ call_internal_pm_session_create_for_vault(state, &external_vault_profile, customer_id).await.unwrap_or_else(|err| {router_env::logger::warn!(@@ -567,19 +573,20 @@ pub async fn fetch_external_vault_details(customer: &Option<domain::Customer>,storage_type: common_enums::StorageType,) -> RouterResult<Option<api::VaultSessionDetails>> {- let external_vault_source = profile+ // In platform flows the external vault configuration and its MCA live on the platform+ // (provider) merchant's profile, not on the payment profile; resolve it first. For standard+ // merchants this resolves to the supplied profile and the provider is the merchant itself.+ let external_vault_profile =+ helpers::resolve_provider_profile(state, platform, profile).await?;+ let external_vault_source = external_vault_profile.external_vault_connector_details.as_ref().map(|details| &details.vault_connector_id);let merchant_connector_account =domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(- helpers::get_merchant_connector_account_v2(- state,- platform.get_processor(),- external_vault_source,- )- .await?,+ helpers::get_provider_mca_v2(state, platform.get_provider(), external_vault_source)+ .await?,));// Connector-customer creation is optional. For the guest flow (no customer) we skip itdiff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rsindex 74a23e0556..1f16353bc0 100644--- a/crates/router/src/routes/admin.rs+++ b/crates/router/src/routes/admin.rs@@ -560,21 +560,23 @@ pub async fn connector_create(state,&req,payload,- |state, auth_data, req, _| {- create_connector(+ |state, auth_data, req, _| async move {+ Box::pin(create_connector(state,req,auth_data.platform.get_processor().clone(),auth_data.profile.map(|profile| profile.get_id().clone()),- )+ ))+ .await},auth::auth_type(- &auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),+ &auth::ApiKeyAuthWithMerchantIdFromRouteAllowPlatform(merchant_id.clone()),&auth::JWTAndEmbeddedAuth {merchant_id_from_route: Some(merchant_id.clone()),permission: Some(Permission::ProfileConnectorWrite),allow_connected: true,- allow_platform: false,+ // Platform merchants create the external (vault) connector on themselves.+ allow_platform: true,},req.headers(),),@@ -599,15 +601,22 @@ pub async fn connector_create(state,&req,payload,- |state, auth_data: auth::AuthenticationData, req, _| {- create_connector(state, req, auth_data.platform.get_processor().clone(), None)+ |state, auth_data: auth::AuthenticationData, req, _| async move {+ Box::pin(create_connector(+ state,+ req,+ auth_data.platform.get_processor().clone(),+ None,+ ))+ .await},auth::auth_type(&auth::AdminApiAuthWithMerchantIdFromHeader,&auth::JWTAuthMerchantFromHeader {required_permission: Permission::MerchantConnectorWrite,allow_connected: true,- allow_platform: false,+ // Platform merchants create the external (vault) connector on themselves.+ allow_platform: true,},req.headers(),),@@ -650,7 +659,7 @@ pub async fn connector_retrieve()},auth::auth_type(- &auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),+ &auth::ApiKeyAuthWithMerchantIdFromRouteAllowPlatform(merchant_id.clone()),&auth::JWTAndEmbeddedAuth {merchant_id_from_route: Some(merchant_id.clone()),// This should ideally be ProfileConnectorRead, but since this API responds with@@ -658,7 +667,7 @@ pub async fn connector_retrieve(// TODO: Convert this to ProfileConnectorRead once data is masked.permission: Some(Permission::ProfileConnectorWrite),allow_connected: true,- allow_platform: false,+ allow_platform: true,},req.headers(),),@@ -760,12 +769,12 @@ pub async fn connector_list(list_payment_connectors(state, auth.platform.get_processor().clone(), None)},auth::auth_type(- &auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),+ &auth::ApiKeyAuthWithMerchantIdFromRouteAllowPlatform(merchant_id.clone()),&auth::JWTAuthMerchantFromRoute {merchant_id,required_permission: Permission::MerchantConnectorRead,allow_connected: true,- allow_platform: false,+ allow_platform: true,},req.headers(),),@@ -800,12 +809,12 @@ pub async fn connector_list_profile()},auth::auth_type(- &auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),+ &auth::ApiKeyAuthWithMerchantIdFromRouteAllowPlatform(merchant_id.clone()),&auth::JWTAndEmbeddedAuth {merchant_id_from_route: Some(merchant_id),permission: Some(Permission::ProfileConnectorRead),allow_connected: true,- allow_platform: false,+ allow_platform: true,},req.headers(),),@@ -846,12 +855,12 @@ pub async fn connector_update()},auth::auth_type(- &auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),+ &auth::ApiKeyAuthWithMerchantIdFromRouteAllowPlatform(merchant_id.clone()),&auth::JWTAndEmbeddedAuth {merchant_id_from_route: Some(merchant_id.clone()),permission: Some(Permission::ProfileConnectorWrite),allow_connected: true,- allow_platform: false,+ allow_platform: true,},req.headers(),),diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rsindex 28d5df800e..6f20e4b617 100644--- a/crates/router/src/routes/profiles.rs+++ b/crates/router/src/routes/profiles.rs@@ -273,7 +273,7 @@ pub async fn profile_update()},auth::auth_type(- &auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),+ &auth::ApiKeyAuthWithMerchantIdFromRouteAllowPlatform(merchant_id.clone()),&auth::JWTAuthMerchantAndProfileFromRoute {merchant_id: merchant_id.clone(),profile_id: profile_id.clone(),@@ -337,7 +337,7 @@ pub async fn profile_update(&auth::JWTAuthMerchantFromHeader {required_permission: permissions::Permission::MerchantAccountWrite,allow_connected: true,- allow_platform: false,+ allow_platform: true,},req.headers(),),@@ -563,12 +563,12 @@ pub async fn payment_connector_list_profile()},auth::auth_type(- &auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone()),+ &auth::ApiKeyAuthWithMerchantIdFromRouteAllowPlatform(merchant_id.clone()),&auth::JWTAuthMerchantFromRoute {merchant_id,required_permission: permissions::Permission::ProfileConnectorRead,allow_connected: true,- allow_platform: false,+ allow_platform: true,},req.headers(),),diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 3e08b8bc24..1d882bc2f8 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -831,6 +831,37 @@ impl GetAuthType for ApiKeyAuthWithMerchantIdFromRoute {}}+#[cfg(feature = "v1")]+/// Shared API-key authentication for profile and connector CRUD operations keyed off a+/// merchant id from the route. `allow_platform_self_operation` controls whether a platform+/// merchant may perform the operation on its own resources (e.g. configuring external vault).+async fn api_key_auth_with_merchant_id_from_route<A>(+ merchant_id_from_route: &id_type::MerchantId,+ allow_platform_self_operation: bool,+ request_headers: &HeaderMap,+ state: &A,+) -> RouterResult<(AuthenticationData, AuthenticationType)>+where+ A: SessionStateInfo + Sync,+{+ let api_auth = ApiKeyAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation,+ };+ let (auth_data, auth_type): (AuthenticationData, AuthenticationType) = api_auth+ .authenticate_and_fetch(request_headers, state)+ .await?;++ let processor_merchant_id = auth_data.platform.get_processor().get_account().get_id();++ fp_utils::when(merchant_id_from_route != processor_merchant_id, || {+ Err(report!(errors::ApiErrorResponse::Unauthorized))+ .attach_printable("Merchant ID from route and Processor Merchant Id do not match")+ })?;++ Ok((auth_data, auth_type))+}+#[cfg(feature = "v1")]#[async_trait]impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuthWithMerchantIdFromRoute@@ -842,24 +873,35 @@ whererequest_headers: &HeaderMap,state: &A,) -> RouterResult<(AuthenticationData, AuthenticationType)> {- // This is currently used for profile and connector CRUD operations- let api_auth = ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: false,- };- let (auth_data, auth_type): (AuthenticationData, AuthenticationType) = api_auth- .authenticate_and_fetch(request_headers, state)- .await?;+ api_key_auth_with_merchant_id_from_route(&self.0, false, request_headers, state).await+ }+}- let merchant_id_from_route = self.0.clone();- let processor_merchant_id = auth_data.platform.get_processor().get_account().get_id();+/// Same as [`ApiKeyAuthWithMerchantIdFromRoute`] but also permits a platform merchant to+/// operate on its own resources. Used by endpoints the platform merchant needs to configure+/// and manage its external vault (connector create/retrieve/update/list, profile update).+pub struct ApiKeyAuthWithMerchantIdFromRouteAllowPlatform(pub id_type::MerchantId);- if merchant_id_from_route != *processor_merchant_id {- return Err(report!(errors::ApiErrorResponse::Unauthorized))- .attach_printable("Merchant ID from route and Processor Merchant Id do not match");- }+#[cfg(feature = "partial-auth")]+impl GetAuthType for ApiKeyAuthWithMerchantIdFromRouteAllowPlatform {+ fn get_auth_type(&self) -> detached::PayloadType {+ detached::PayloadType::ApiKey+ }+}- Ok((auth_data, auth_type))+#[cfg(feature = "v1")]+#[async_trait]+impl<A> AuthenticateAndFetch<AuthenticationData, A>+ for ApiKeyAuthWithMerchantIdFromRouteAllowPlatform+where+ A: SessionStateInfo + Sync,+{+ async fn authenticate_and_fetch(+ &self,+ request_headers: &HeaderMap,+ state: &A,+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {+ api_key_auth_with_merchant_id_from_route(&self.0, true, request_headers, state).await}}diff --git a/cypress-tests/cypress/e2e/spec/Platform/00003-ConnectorSetup.cy.js b/cypress-tests/cypress/e2e/spec/Platform/00003-ConnectorSetup.cy.jsindex f2d5be9d6b..9b98f4aef6 100644--- a/cypress-tests/cypress/e2e/spec/Platform/00003-ConnectorSetup.cy.js+++ b/cypress-tests/cypress/e2e/spec/Platform/00003-ConnectorSetup.cy.js@@ -223,8 +223,10 @@ describe("Connector Setup for Connected Merchants", () => {});});- context("Platform Merchant Cannot Create Connector", () => {- it("platform-merchant-cannot-create-connector", () => {+ context("Platform Merchant Cannot Create Payment Connector", () => {+ // Platform merchants may only configure vault connectors on themselves+ // (used for external vault). Creating a payment processor connector must be rejected.+ it("platform-merchant-cannot-create-payment-connector", () => {const savedMerchantId = globalState.get("merchantId");const savedProfileId = globalState.get("profileId");@@ -245,7 +247,7 @@ describe("Connector Setup for Connected Merchants", () => {globalState,"profile", // profilePrefix"merchantConnector", // mcaPrefix- 400 // expectedStatus+ 422 // expectedStatus (InvalidRequestData -> Unprocessable Entity));cy.then(() => {