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(merchant_account): add integration_type and validate X-Integration-Type against it (#14173)
Prasunna Soppa4dedcd27ab8d
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex 369d08bb54..c56eff2d75 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2672,6 +2672,11 @@ pt_mapping_outgoing_connector_webhooks = { value = { default_mapping = { frequen"vaulting.save_wallet_decrypted_data" = { value = false, schema = { type = "boolean" }, description = "Whether to save wallet decrypted data", change_reason = "Initial setup" }"vaulting.fingerprint_secret" = { value = "", schema = { type = "string" }, description = "Fingerprint secret used as a migration fallback for merchant accounts", change_reason = "Retain during merchant account migration" }"payments.should_call_gsm" = { value = false, schema = { type = "boolean" }, description = "Whether to call GSM (Global Status Mapping) for auto-retries on payment failure", change_reason = "Initial setup" }+"system.payment_integration_type" = { value = "client", schema = { type = "string", enum = [+ "client",+ "server",+ "client_and_server",+] }, description = "Which integration the merchant builds its checkout with. The X-Integration-Type header on payment requests must match it: 'client' rejects 'server', 'server' requires 'server' (an absent header reads as 'client'), 'client_and_server' accepts either. Defaults to 'client', so a merchant must opt in before it can request the server response shape. Override per processor_merchant_id.", change_reason = "Merchant-level gate for the server-integration response shape" }"system.payment_method_integration_type" = { value = "vault_then_pay", schema = { enum = ["vault_then_pay","pay_then_vault",diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex aa00cdfa6d..cabbea188a 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -10822,6 +10822,14 @@ impl IntegrationType {pub fn is_server(self) -> bool {matches!(self, Self::Server)}++ /// The header spelling of this value.+ pub fn as_header_value(self) -> &'static str {+ match self {+ Self::Client => "client",+ Self::Server => "server",+ }+ }}/// Wallet session tokens, or the error that prevented them being minted.diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 4568f31fe9..de0451d423 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -9,8 +9,8 @@ use std::{};pub use accounts::{- MerchantAccountRequestType, MerchantAccountType, MerchantProductType, OrganizationType,- ResourceRequestorType, ResourceType,+ MerchantAccountRequestType, MerchantAccountType, MerchantIntegrationType, MerchantProductType,+ OrganizationType, ResourceRequestorType, ResourceType,};use diesel::{backend::Backend,diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rsindex 6c05b5cc75..105022434b 100644--- a/crates/common_enums/src/enums/accounts.rs+++ b/crates/common_enums/src/enums/accounts.rs@@ -49,6 +49,32 @@ pub enum MerchantAccountType {Connected,}+/// Which `X-Integration-Type` header values a merchant may send, from Superposition+/// (`system.payment_integration_type`). Defaults to `client`: the server shape is opt-in.+#[derive(+ Clone,+ Copy,+ Debug,+ Default,+ Eq,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+)]+#[strum(serialize_all = "snake_case")]+#[serde(rename_all = "snake_case")]+pub enum MerchantIntegrationType {+ /// The default: the header must be `client` or absent.+ #[default]+ Client,+ /// The header must be `server`.+ Server,+ /// Any header value is accepted.+ ClientAndServer,+}+#[derive(Clone,Copy,diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 245e63c8de..e1e086db19 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -421,6 +421,8 @@ pub mod superposition {pub const OFFER_ENGINE_ENABLED: &str = "offer_engine.enabled";/// Offer Engine credential source key: `"none"` skips Offer Engine, `"application"` uses the static app config, `"merchant"` uses per-merchant credentials.pub const OFFER_ENGINE_CREDENTIAL_SOURCE: &str = "offer_engine.credential_source";+ /// Merchant integration type key: `"client"` (default), `"server"` or `"client_and_server"`. The `X-Integration-Type` header on payment requests must match it.+ pub const MERCHANT_INTEGRATION_TYPE: &str = "system.payment_integration_type";/// Account Updater master gate key: `false` (default) disables all Account Updater calls.pub const ACCOUNT_UPDATER_ENABLED: &str = "account_updater.enabled";/// Account Updater credential source key: `"none"` skips Account Updater, `"application"` uses the static application config.diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex 3877cacade..188f60660e 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -962,6 +962,27 @@ impl DatabaseBackedConfig for OfferEngineCredentialSource {const KEY: &'static str = "offer_engine.credential_source";}+config! {+ superposition_key = MERCHANT_INTEGRATION_TYPE,+ output = common_enums::MerchantIntegrationType,+ default = common_enums::MerchantIntegrationType::Client,+ string_enum = true,+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantId,+ targeting_key = id_type::PaymentId+}++impl DatabaseBackedConfig for MerchantIntegrationType {+ const KEY: &'static str = "system.payment_integration_type";++ // Superposition gets both merchant ids; this is only the `configs`-table fallback, keyed on+ // the processor merchant like `requires_cvv` and `client_session_validation_enabled`.+ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_processor_merchant_id()+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))+ }+}+#[cfg(feature = "v2")]config! {superposition_key = ACCOUNT_UPDATER_ENABLED,diff --git a/crates/router/src/core/payments/update_context.rs b/crates/router/src/core/payments/update_context.rsindex aff3066a14..fb65ddcfee 100644--- a/crates/router/src/core/payments/update_context.rs+++ b/crates/router/src/core/payments/update_context.rs@@ -19,7 +19,7 @@ use error_stack::ResultExt;use router_env::{instrument, logger, tracing};use crate::{- core::{errors, payment_methods::client as pm_client, payments},+ core::{configs::dimension_state, errors, payment_methods::client as pm_client, payments},routes::{app::ReqState, SessionState},services::{ApplicationResponse, AuthFlow},types::{api as api_types, domain},@@ -68,6 +68,47 @@ pub fn integration_type_from_headers(integration_type}+/// The integration type the merchant is configured for, defaulting to `client`.+pub async fn merchant_integration_type(+ state: &SessionState,+ platform: &domain::Platform,+) -> common_enums::MerchantIntegrationType {+ dimension_state::Dimensions::new()+ .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())+ .get_merchant_integration_type(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await+}++/// Rejects a header that does not match the merchant's integration type. An absent header reads+/// as `client`, so a `server` merchant must send it.+pub fn validate_integration_type(+ header: IntegrationType,+ merchant: common_enums::MerchantIntegrationType,+) -> errors::RouterResult<()> {+ let allowed = match merchant {+ common_enums::MerchantIntegrationType::ClientAndServer => true,+ common_enums::MerchantIntegrationType::Client => !header.is_server(),+ common_enums::MerchantIntegrationType::Server => header.is_server(),+ };++ common_utils::fp_utils::when(!allowed, || {+ Err(error_stack::report!(+ errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "`{}` header value `{}` does not match the merchant integration type `{merchant}`",+ consts::X_INTEGRATION_TYPE,+ header.as_header_value()+ ),+ }+ ))+ })+}+/// Builds the error payload a degraded section carries, from the same error the standalone/// endpoint would have surfaced.fn section_error(diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex 5ad7e10f6f..d971eff44d 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -134,14 +134,23 @@ pub async fn payments_create(),};+ let integration_type = update_context::integration_type_from_headers(req.headers());+Box::pin(api::server_wrap(flow,state,&req,payload,- |mut state, auth: auth::AuthenticationData, req, req_state| {+ move |mut state, auth: auth::AuthenticationData, req, req_state| {let header_payload = header_payload.clone();async move {+ let merchant_integration_type =+ update_context::merchant_integration_type(&state, &auth.platform).await;+ update_context::validate_integration_type(+ integration_type,+ merchant_integration_type,+ )?;+let metrics_start = req.confirm.is_some_and(|confirm| confirm)@@ -943,6 +952,13 @@ pub async fn payments_update(move |state, auth: auth::AuthenticationData, req, req_state| {let header_payload = header_payload.clone();async move {+ let merchant_integration_type =+ update_context::merchant_integration_type(&state, &auth.platform).await;+ update_context::validate_integration_type(+ integration_type,+ merchant_integration_type,+ )?;+let profile_id = auth.profile.map(|profile| profile.get_id().clone());// Only the enrichment path needs these afterwards. A client update — the vast