Skip to content

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

feat(platform): implement customer sharing model and refactor API key authentication (#10387)

Sandeep Kumarbb1c0204613b
diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
index a7cadedb47..84550c1979 100644
--- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs
@@ -303,6 +303,10 @@ pub enum ApiErrorResponse {
},
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_48", message = "The Status token for connector costumer id {resource} is locked by different PaymentIntent ID")]
InvalidPaymentIdProvided { resource: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_49", message = "API does not support connected account operation")]
+ ConnectedAccountAuthNotSupported,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_50", message = "Invalid connected account operation")]
+ InvalidConnectedOperation,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")]
WebhookAuthenticationFailed,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")]
@@ -665,6 +669,12 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::CookieNotFound => {
AER::Unauthorized(ApiError::new("IR", 42, "Cookies are not found in the request", None))
},
+ Self::PlatformAccountAuthNotSupported => {
+ AER::BadRequest(ApiError::new("IR", 43, "API does not support platform account operation", None))
+ }
+ Self::InvalidPlatformOperation => {
+ AER::Unauthorized(ApiError::new("IR", 44, "Invalid platform account operation", None))
+ }
Self::ExternalVaultFailed => {
AER::BadRequest(ApiError::new("IR", 45, "External Vault failed while processing with connector.", None))
},
@@ -677,6 +687,12 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::InvalidPaymentIdProvided {resource} => {
AER::NotFound(ApiError::new("IR", 48, format!("The Status token for connector costumer id {resource} is locked by different PaymentIntent ID"), None))
},
+ Self::ConnectedAccountAuthNotSupported => {
+ AER::BadRequest(ApiError::new("IR", 49, "API does not support connected account operation", None))
+ }
+ Self::InvalidConnectedOperation => {
+ AER::Unauthorized(ApiError::new("IR", 50, "Invalid connected account operation", None))
+ }
Self::WebhookAuthenticationFailed => {
AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
}
@@ -708,12 +724,6 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
..Default::default()
})
)),
- Self::PlatformAccountAuthNotSupported => {
- AER::BadRequest(ApiError::new("IR", 43, "API does not support platform operation", None))
- }
- Self::InvalidPlatformOperation => {
- AER::Unauthorized(ApiError::new("IR", 44, "Invalid platform account operation", None))
- }
Self::TokenizationRecordNotFound{ id } => {
AER::NotFound(ApiError::new("HE", 2, format!("Tokenization record not found for the given token_id '{id}' "), None))
}
diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs
index c2a2da4050..f0a57cf590 100644
--- a/crates/router/src/compatibility/stripe/customers.rs
+++ b/crates/router/src/compatibility/stripe/customers.rs
@@ -14,9 +14,11 @@ use crate::{
core::{api_locking, customers, payment_methods::cards},
routes,
services::{api, authentication as auth},
- types::api::{customers as customer_types, payment_methods},
+ types::{
+ api::{customers as customer_types, payment_methods},
+ domain,
+ },
};
-
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customer_create(
@@ -51,8 +53,8 @@ pub async fn customer_create(
&req,
create_cust_req,
|state, auth: auth::AuthenticationData, req, _| {
- let platform = auth.into();
- customers::create_customer(state, platform, req, None)
+ let platform: domain::Platform = auth.into();
+ customers::create_customer(state, platform.get_provider().clone(), req, None)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
@@ -89,8 +91,8 @@ pub async fn customer_retrieve(
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
- let platform = auth.into();
- customers::retrieve_customer(state, platform, None, customer_id)
+ let platform: domain::Platform = auth.into();
+ customers::retrieve_customer(state, platform.get_provider().clone(), None, customer_id)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
@@ -141,8 +143,8 @@ pub async fn customer_update(
&req,
request_internal,
|state, auth: auth::AuthenticationData, request_internal, _| {
- let platform = auth.into();
- customers::update_customer(state, platform, request_internal)
+ let platform: domain::Platform = auth.into();
+ customers::update_customer(state, platform.get_provider().clone(), request_internal)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index cc426b32d7..65b05b39b4 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -283,6 +283,10 @@ pub enum StripeErrorCode {
PlatformBadRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")]
PlatformUnauthorizedRequest,
+ #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Connected Bad Request")]
+ ConnectedBadRequest,
+ #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Connected Unauthorized Request")]
+ ConnectedUnauthorizedRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Profile Acquirer not found")]
ProfileAcquirerNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "Subscription Error", message = "Subscription operation: {operation} failed with connector")]
@@ -693,6 +697,10 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
}
errors::ApiErrorResponse::PlatformAccountAuthNotSupported => Self::PlatformBadRequest,
errors::ApiErrorResponse::InvalidPlatformOperation => Self::PlatformUnauthorizedRequest,
+ errors::ApiErrorResponse::ConnectedAccountAuthNotSupported => Self::ConnectedBadRequest,
+ errors::ApiErrorResponse::InvalidConnectedOperation => {
+ Self::ConnectedUnauthorizedRequest
+ }
errors::ApiErrorResponse::ProfileAcquirerNotFound { .. } => {
Self::ProfileAcquirerNotFound
}
@@ -712,7 +720,9 @@ impl actix_web::ResponseError for StripeErrorCode {
use reqwest::StatusCode;
match self {
- Self::Unauthorized | Self::PlatformUnauthorizedRequest => StatusCode::UNAUTHORIZED,
+ Self::Unauthorized
+ | Self::PlatformUnauthorizedRequest
+ | Self::ConnectedUnauthorizedRequest => StatusCode::UNAUTHORIZED,
Self::InvalidRequestUrl | Self::GenericNotFoundError { .. } => StatusCode::NOT_FOUND,
Self::ParameterUnknown { .. } | Self::HyperswitchUnprocessableEntity { .. } => {
StatusCode::UNPROCESSABLE_ENTITY
@@ -777,6 +787,7 @@ impl actix_web::ResponseError for StripeErrorCode {
| Self::PaymentMethodDeleteFailed
| Self::ExtendedCardInfoNotFound
| Self::PlatformBadRequest
+ | Self::ConnectedBadRequest
| Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST,
Self::RefundFailed
| Self::PayoutFailed
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 0dad3b1bcf..82403c8871 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -41,7 +41,7 @@ pub const REDACTED: &str = "Redacted";
#[instrument(skip(state))]
pub async fn create_customer(
state: SessionState,
- platform: domain::Platform,
+ provider: domain::Provider,
customer_data: customers::CustomerRequest,
connector_customer_details: Option<Vec<payment_methods_domain::ConnectorCustomerDetails>>,
) -> errors::CustomerResponse<customers::CustomerResponse> {
@@ -50,13 +50,13 @@ pub async fn create_customer(
let merchant_reference_id = customer_data.get_merchant_reference_id();
- let merchant_id = platform.get_processor().get_account().get_id();
+ let merchant_id = provider.get_account().get_id();
let merchant_reference_id_customer = MerchantReferenceIdForCustomer {
merchant_reference_id: merchant_reference_id.as_ref(),
merchant_id,
- merchant_account: platform.get_processor().get_account(),
- key_store: platform.get_processor().get_key_store(),
+ merchant_account: provider.get_account(),
+ key_store: provider.get_key_store(),
};
// We first need to validate whether the customer with the given customer id already exists
@@ -74,7 +74,7 @@ pub async fn create_customer(
&connector_customer_details,
db,
&merchant_reference_id,
- &platform,
+ &provider,
key_manager_state,
&state,
)
@@ -83,8 +83,8 @@ pub async fn create_customer(
let customer = db
.insert_customer(
domain_customer,
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
+ provider.get_key_store(),
+ provider.get_account().storage_scheme,
)
.await
.to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?;
@@ -101,7 +101,7 @@ trait CustomerCreateBridge {
>,
db: &'a dyn StorageInterface,
merchant_reference_id: &'a Option<id_type::CustomerId>,
- platform: &'a domain::Platform,
+ provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>;
@@ -122,27 +122,22 @@ impl CustomerCreateBridge for customers::CustomerRequest {
>,
db: &'a dyn StorageInterface,
merchant_reference_id: &'a Option<id_type::CustomerId>,
- platform: &'a domain::Platform,
+ provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
// Setting default billing address to Db
let address = self.get_address();
- let merchant_id = platform.get_processor().get_account().get_id();
- let key = platform
- .get_processor()
- .get_key_store()
- .key
- .get_inner()
- .peek();
+ let merchant_id = provider.get_account().get_id();
+ let key = provider.get_key_store().key.get_inner().peek();
let customer_billing_address_struct = AddressStructForDbEntry {
address: address.as_ref(),
customer_data: self,
merchant_id,
customer_id: merchant_reference_id.as_ref(),
- storage_scheme: platform.get_processor().get_account().storage_scheme,
- key_store: platform.get_processor().get_key_store(),
+ storage_scheme: provider.get_account().storage_scheme,
+ key_store: provider.get_key_store(),
state,
};
@@ -163,7 +158,7 @@ impl CustomerCreateBridge for customers::CustomerRequest {
},
),
),
- Identifier::Merchant(platform.get_processor().get_key_store().merchant_id.clone()),
+ Identifier::Merchant(provider.get_key_store().merchant_id.clone()),
key,
)
.await
@@ -238,18 +233,14 @@ impl CustomerCreateBridge for customers::CustomerRequest {
>,
_db: &'a dyn StorageInterface,
merchant_reference_id: &'a Option<id_type::CustomerId>,
- platform: &'a domain::Platform,
+ provider: &'a domain::Provider,
key_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
let default_customer_billing_address = self.get_default_customer_billing_address();
let encrypted_customer_billing_address = default_customer_billing_address
.async_map(|billing_address| {
- create_encrypted_data(
- key_state,
- platform.get_processor().get_key_store(),
- billing_address,
- )
+ create_encrypted_data(key_state, provider.get_key_store(), billing_address)
})
.await
.transpose()
@@ -258,24 +249,15 @@ impl CustomerCreateBridge for customers::CustomerRequest {
let default_customer_shipping_address = self.get_default_customer_shipping_address();
let encrypted_customer_shipping_address = default_customer_shipping_address
.async_map(|shipping_address| {
- create_encrypted_data(
- key_state,
- platform.get_processor().get_key_store(),
- shipping_address,
- )
+ create_encrypted_data(key_state, provider.get_key_store(), shipping_address)
})
.await
.transpose()
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt default customer shipping address")?;
- let merchant_id = platform.get_processor().get_account().get_id().clone();
- let key = platform
- .get_processor()
- .get_key_store()
- .key
- .get_inner()
- .peek();
+ let merchant_id = provider.get_account().get_id().clone();
+ let key = provider.get_key_store().key.get_inner().peek();
let encrypted_data = types::crypto_operation(
key_state,
@@ -290,7 +272,7 @@ impl CustomerCreateBridge for customers::CustomerRequest {
},
),
),
- Identifier::Merchant(platform.get_processor().get_key_store().merchant_id.clone()),
+ Identifier::Merchant(provider.get_key_store().merchant_id.clone()),
key,
)
.await
@@ -506,7 +488,7 @@ impl<'a> MerchantReferenceIdForCustomer<'a> {
#[instrument(skip(state))]
pub async fn retrieve_customer(
state: SessionState,
- platform: domain::Platform,
+ provider: domain::Provider,
_profile_id: Option<id_type::ProfileId>,
customer_id: id_type::CustomerId,
) -> errors::CustomerResponse<customers::CustomerResponse> {
@@ -515,9 +497,9 @@ pub async fn retrieve_customer(
let response = db
.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&customer_id,
- platform.get_processor().get_account().get_id(),
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
+ provider.get_account().get_id(),
+ provider.get_key_store(),
+ provider.get_account().storage_scheme,
)
.await
.switch()?
@@ -525,7 +507,7 @@ pub async fn retrieve_customer(
let address = match &response.address_id {
Some(address_id) => Some(api_models::payments::AddressDetails::from(
- db.find_address_by_address_id(address_id, platform.get_processor().get_key_store())
+ db.find_address_by_address_id(address_id, provider.get_key_store())
.await
.switch()?,
)),
@@ -540,7 +522,7 @@ pub async fn retrieve_customer(
#[instrument(skip(state))]
pub async fn retrieve_customer(
state: SessionState,
- platform: domain::Platform,
+ provider: domain::Provider,
id: id_type::GlobalCustomerId,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
@@ -548,8 +530,8 @@ pub async fn retrieve_customer(
let response = db
.find_customer_by_global_id(
&id,
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
+ provider.get_key_store(),
+ provider.get_account().storage_scheme,
)
.await
.switch()?;
@@ -562,9 +544,8 @@ pub async fn retrieve_customer(
#[instrument(skip(state))]
pub async fn list_customers(
state: SessionState,
- merchant_id: id_type::MerchantId,
+ provider: domain::Provider,
_profile_id_list: Option<Vec<id_type::ProfileId>>,
- key_store: domain::MerchantKeyStore,
request: customers::CustomerListRequest,
) -> errors::CustomerResponse<Vec<customers::CustomerResponse>> {
let db = state.store.as_ref();
@@ -579,7 +560,11 @@ pub async fn list_customers(
};
let domain_customers = db
- .list_customers_by_merchant_id(&merchant_id, &key_store, customer_list_constraints)
+ .list_customers_by_merchant_id(
+ provider.get_account().get_id(),
+ provider.get_key_store(),
+ customer_list_constraints,
+ )
.await
.switch()?;
@@ -601,8 +586,7 @@ pub async fn list_customers(
#[instrument(skip(state))]
pub async fn list_customers_with_count(
state: SessionState,
- merchant_id: id_type::MerchantId,
- key_store: domain::MerchantKeyStore,
+ provider: domain::Provider,
request: customers::CustomerListRequestWithConstraints,
) -> errors::CustomerResponse<customers::CustomerListResponse> {
let db = state.store.as_ref();
@@ -618,8 +602,8 @@ pub async fn list_customers_with_count(
let domain_customers = db
.list_customers_by_merchant_id_with_count(
- &merchant_id,
- &key_store,
+ provider.get_account().get_id(),
+ provider.get_key_store(),
customer_list_constraints,
)
.await
@@ -1040,7 +1024,7 @@ impl CustomerDeleteBridge for id_type::CustomerId {
#[instrument(skip(state))]
pub async fn update_customer(
state: SessionState,
- platform: domain::Platform,
+ provider: domain::Provider,
update_customer: customers::CustomerUpdateRequestInternal,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
@@ -1050,15 +1034,15 @@ pub async fn update_customer(
#[cfg(feature = "v1")]
let verify_id_for_update_customer = VerifyIdForUpdateCustomer {
merchant_reference_id: &update_customer.customer_id,
- merchant_account: platform.get_processor().get_account(),
- key_store: platform.get_processor().get_key_store(),
+ merchant_account: provider.get_account(),
+ key_store: provider.get_key_store(),
};
#[cfg(feature = "v2")]
let verify_id_for_update_customer = VerifyIdForUpdateCustomer {
id: &update_customer.id,
- merchant_account: platform.get_processor().get_account(),
- key_store: platform.get_processor().get_key_store(),
+ merchant_account: provider.get_account(),
+ key_store: provider.get_key_store(),
key_manager_state,
};
@@ -1071,7 +1055,7 @@ pub async fn update_customer(
.create_domain_model_from_request(
&None,
db,
- &platform,
+ &provider,
key_manager_state,
&state,
&customer,
@@ -1089,7 +1073,7 @@ trait CustomerUpdateBridge {
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
db: &'a dyn StorageInterface,
- platform: &'a domain::Platform,
+ provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
domain_customer: &'a domain::Customer,
@@ -1246,15 +1230,15 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
db: &'a dyn StorageInterface,
- platform: &'a domain::Platform,
+ provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
domain_customer: &'a domain::Customer,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
let update_address_for_update_customer = AddressStructForDbUpdate {
update_customer: self,
- merchant_account: platform.get_processor().get_account(),
- key_store: platform.get_processor().get_key_store(),
+ merchant_account: provider.get_account(),
+ key_store: provider.get_key_store(),
state,
domain_customer,
};
@@ -1263,12 +1247,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
.update_address_if_sent(db)
.await?;
- let key = platform
- .get_processor()
- .get_key_store()
- .key
- .get_inner()
- .peek();
+ let key = provider.get_key_store().key.get_inner().peek();
let encrypted_data = types::crypto_operation(
key_manager_state,
@@ -1286,7 +1265,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
},
),
),
- Identifier::Merchant(platform.get_processor().get_key_store().merchant_id.clone()),
+ Identifier::Merchant(provider.get_key_store().merchant_id.clone()),
key,
)
.await
@@ -1300,7 +1279,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
let response = db
.update_customer_by_customer_id_merchant_id(
domain_customer.customer_id.to_owned(),
- platform.get_processor().get_account().get_id().to_owned(),
+ provider.get_account().get_id().to_owned(),
domain_customer.to_owned(),
storage::CustomerUpdate::Update {
name: encryptable_customer.name,
@@ -1321,8 +1300,8 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
address_id: address.clone().map(|addr| addr.address_id),
last_modified_by: None,
},
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
+ provider.get_key_store(),
+ provider.get_account().storage_scheme,
)
.await
.switch()?;
@@ -1350,7 +1329,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
db: &'a dyn StorageInterface,
- platform: &'a domain::Platform,
+ provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
domain_customer: &'a domain::Customer,
@@ -1358,11 +1337,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
let default_billing_address = self.get_default_customer_billing_address();
let encrypted_customer_billing_address = default_billing_address
.async_map(|billing_address| {
- create_encrypted_data(
- key_manager_state,
- platform.get_processor().get_key_store(),
- billing_address,
- )
+ create_encrypted_data(key_manager_state, provider.get_key_store(), billing_address)
})
.await
.transpose()
@@ -1374,7 +1349,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
.async_map(|shipping_address| {
create_encrypted_data(
key_manager_state,
- platform.get_processor().get_key_store(),
+ provider.get_key_store(),
shipping_address,
)
})
@@ -1383,12 +1358,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt default customer shipping address")?;
- let key = platform
- .get_processor()
- .get_key_store()
- .key
- .get_inner()
- .peek();
+ let key = provider.get_key_store().key.get_inner().peek();
let encrypted_data = types::crypto_operation(
key_manager_state,
@@ -1406,7 +1376,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
},
),
),
- Identifier::Merchant(platform.get_processor().get_key_store().merchant_id.clone()),
+ Identifier::Merchant(provider.get_key_store().merchant_id.clone()),
key,
)
.await
@@ -1443,8 +1413,8 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
status: None,
last_modified_by: None,
})),
- platform.get_processor().get_key_store(),
- platform.get_processor().get_account().storage_scheme,
+ provider.get_key_store(),
+ provider.get_account().storage_scheme,
)
.await
.switch()?;
@@ -1469,7 +1439,7 @@ pub async fn migrate_customers(
for customer_migration in customers_migration {
match create_customer(
state.clone(),
- platform.clone(),
+ platform.get_provider().clone(),
customer_migration.customer,
customer_migration.connector_customer_details,
)
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index de1c2cee99..292aeef763 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -6,7 +6,7 @@ use super::app::AppState;
use crate::{
core::{api_locking, customers::*},
services::{api, authentication as auth, authorization::permissions::Permission},
- types::api::customers,
+ types::{api::customers, domain},
};
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
@@ -22,8 +22,8 @@ pub async fn customers_create(
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
- let platform = auth.into();
- create_customer(state, platform, req, None)
+ let platform: domain::Platform = auth.into();
+ create_customer(state, platform.get_provider().clone(), req, None)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
@@ -53,13 +53,13 @@ pub async fn customers_create(
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, req, _| {
- let platform = auth.into();
- create_customer(state, platform, req, None)
+ let platform: domain::Platform = auth.into();
+ create_customer(state, platform.get_provider().clone(), req, None)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
- is_connected_allowed: false,
- is_platform_allowed: false,
+ is_connected_allowed: true,
+ is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
@@ -87,7 +87,10 @@ pub async fn customers_retrieve(
permission: Permission::MerchantCustomerRead,
})
} else {
- let api_auth = auth::ApiKeyAuth::default();
+ let api_auth = auth::ApiKeyAuth {
+ is_connected_allowed: true,
+ is_platform_allowed: true,
+ };
match auth::is_ephemeral_auth(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
@@ -100,8 +103,13 @@ pub async fn customers_retrieve(
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
- let platform = auth.clone().into();
- retrieve_customer(state, platform, auth.profile_id, customer_id)
+ let platform: domain::Platform = auth.clone().into();
+ retrieve_customer(
+ state,
+ platform.get_provider().clone(),
+ auth.profile_id,
+ customer_id,
+ )
},
&*auth,
api_locking::LockAction::NotApplicable,
@@ -146,8 +154,8 @@ pub async fn customers_retrieve(
&req,
id,
|state, auth: auth::AuthenticationData, id, _| {
- let platform = auth.into();
- retrieve_customer(state, platform, id)
+ let platform: domain::Platform = auth.into();
+ retrieve_customer(state, platform.get_provider().clone(), id)
},
auth,
api_locking::LockAction::NotApplicable,
@@ -170,13 +178,8 @@ pub async fn customers_list(
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
- list_customers(
- state,
- auth.merchant_account.get_id().to_owned(),
- None,
- auth.key_store,
- request,
- )
+ let platform: domain::Platform = auth.into();
+ list_customers(state, platform.get_provider().clone(), None, request)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
@@ -208,18 +211,13 @@ pub async fn customers_list(
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
- list_customers(
- state,
- auth.merchant_account.get_id().to_owned(),
- None,
- auth.key_store,
- request,
- )
+ let platform: domain::Platform = auth.into();
+ list_customers(state, platform.get_provider().clone(), None, request)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
- is_connected_allowed: false,
- is_platform_allowed: false,
+ is_connected_allowed: true,
+ is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
@@ -247,12 +245,8 @@ pub async fn customers_list_with_count(
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
- list_customers_with_count(
- state,
- auth.merchant_account.get_id().to_owned(),
- auth.key_store,
- request,
- )
+ let platform: domain::Platform = auth.into();
+ list_customers_with_count(state, platform.get_provider().clone(), request)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
@@ -284,17 +278,13 @@ pub async fn customers_list_with_count(
&req,
payload,
|state, auth: auth::AuthenticationData, request, _| {
- list_customers_with_count(
- state,
- auth.merchant_account.get_id().to_owned(),
- auth.key_store,
- request,
- )
+ let platform: domain::Platform = auth.into();
+ list_customers_with_count(state, platform.get_provider().clone(), request)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
- is_connected_allowed: false,
- is_platform_allowed: false,
+ is_connected_allowed: true,
+ is_platform_allowed: true,
}),
&auth::JWTAuth {
permission: Permission::MerchantCustomerRead,
@@ -328,13 +318,13 @@ pub async fn customers_update(
&req,
request_internal,
|state, auth: auth::AuthenticationData, request_internal, _| {
- let platform = auth.into();
- update_customer(state, platform, request_internal)
+ let platform: domain::Platform = auth.into();
+ update_customer(state, platform.get_provider().clone(), request_internal)
},
auth::auth_type(
&auth::ApiKeyAuth {
- is_connected_allowed: false,
- is_platform_allowed: false,
+ is_connected_allowed: true,
+ is_platform_allowed: true,
},
&auth::JWTAuth {
permission: Permission::MerchantCustomerWrite,
@@ -365,8 +355,8 @@ pub async fn customers_update(
&req,
request_internal,
|state, auth: auth::AuthenticationData, request_internal, _| {
- let platform = auth.into();
- update_customer(state, platform, request_internal)
+ let platform: domain::Platform = auth.into();
+ update_customer(state, platform.get_provider().clone(), request_internal)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 7677956799..583c7d243b 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -9,7 +9,7 @@ use api_models::payments;
#[cfg(feature = "payouts")]
use api_models::payouts;
use async_trait::async_trait;
-use common_enums::TokenPurpose;
+use common_enums::{MerchantAccountType, TokenPurpose};
use common_utils::{date_time, fp_utils, id_type};
#[cfg(feature = "v2")]
use diesel_models::ephemeral_key;
@@ -403,6 +403,22 @@ impl GetAuthType for ApiKeyAuth {
}
}
+#[cfg(feature = "partial-auth")]
+pub trait GetMerchantAccessFlags {
+ fn get_is_connected_allowed(&self) -> bool;
+ fn get_is_platform_allowed(&self) -> bool;
+}
+
+#[cfg(feature = "partial-auth")]
+impl GetMerchantAccessFlags for ApiKeyAuth {
+ fn get_is_connected_allowed(&self) -> bool {
+ self.is_connected_allowed
+ }
+ fn get_is_platform_allowed(&self) -> bool {
+ self.is_platform_allowed
+ }
+}
+
//
// # Header Auth
//
@@ -504,54 +520,34 @@ where
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
- let merchant = state
+ let initiator_merchant = state
.store()
.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
- // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
- let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
- get_platform_merchant_account(state, request_headers, merchant).await?
- } else {
- (merchant, None)
- };
-
- if platform_merchant_account.is_some() && !self.is_platform_allowed {
- return Err(report!(
- errors::ApiErrorResponse::PlatformAccountAuthNotSupported
- ))
- .attach_printable("Platform not authorized to access the resource");
- }
-
- let platform_account_with_key_store =
- platform_merchant_account
- .clone()
- .map(|platform_account| PlatformAccountWithKeyStore {
- account: platform_account,
- key_store: key_store.clone(),
- });
-
- let key_store = if platform_merchant_account.is_some() {
- state
- .store()
- .get_merchant_key_store_by_merchant_id(
- merchant.get_id(),
- &state.store().get_master_key().to_vec().into(),
- )
- .await
- .change_context(errors::ApiErrorResponse::Unauthorized)
- .attach_printable("Failed to fetch merchant key store for the merchant id")?
- } else {
- key_store
- };
-
let profile = state
.store()
.find_business_profile_by_profile_id(&key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
+ check_merchant_access(
+ state,
+ initiator_merchant.merchant_account_type,
+ self.is_connected_allowed,
+ self.is_platform_allowed,
+ )?;
+
+ let (merchant, key_store, platform_account_with_key_store) =
+ resolve_merchant_accounts_and_key_stores(
+ state,
+ request_headers,
+ initiator_merchant.clone(),
+ key_store,
+ )
+ .await?;
+
let auth = AuthenticationData {
merchant_account: merchant,
platform_account_with_key_store,
@@ -561,7 +557,7 @@ where
Ok((
auth.clone(),
AuthenticationType::ApiKey {
- merchant_id: auth.merchant_account.get_id().clone(),
+ merchant_id: initiator_merchant.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
@@ -631,47 +627,27 @@ where
})
.change_context(errors::ApiErrorResponse::Unauthorized)?;
- let merchant = state
+ let initiator_merchant = state
.store()
.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
- let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
- get_platform_merchant_account(state, request_headers, merchant).await?
- } else {
- (merchant, None)
- };
-
- if platform_merchant_account.is_some() && !self.is_platform_allowed {
- return Err(report!(
- errors::ApiErrorResponse::PlatformAccountAuthNotSupported
- ))
- .attach_printable("Platform not authorized to access the resource");
- }
-
- let platform_account_with_key_store =
- platform_merchant_account
- .clone()
- .map(|platform_account| PlatformAccountWithKeyStore {
- account: platform_account,
- key_store: key_store.clone(),
- });
-
- let key_store = if platform_account_with_key_store.is_some() {
- state
- .store()
- .get_merchant_key_store_by_merchant_id(
- merchant.get_id(),
- &state.store().get_master_key().to_vec().into(),
- )
- .await
- .change_context(errors::ApiErrorResponse::Unauthorized)
- .attach_printable("Failed to fetch merchant key store for the merchant id")?
- } else {
- key_store
- };
+ check_merchant_access(
+ state,
+ initiator_merchant.merchant_account_type,
+ self.is_connected_allowed,
+ self.is_platform_allowed,
+ )?;
+ let (merchant, key_store, platform_account_with_key_store) =
+ resolve_merchant_accounts_and_key_stores(
+ state,
+ request_headers,
+ initiator_merchant.clone(),
+ key_store,
+ )
+ .await?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_account_with_key_store,
@@ -681,7 +657,7 @@ where
Ok((
auth.clone(),
AuthenticationType::ApiKey {
- merchant_id: auth.merchant_account.get_id().clone(),
+ merchant_id: initiator_merchant.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
@@ -1078,7 +1054,11 @@ where
impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I>
where
A: SessionStateInfo + Sync,
- I: AuthenticateAndFetch<AuthenticationData, A> + GetAuthType + Sync + Send,
+ I: AuthenticateAndFetch<AuthenticationData, A>
+ + GetAuthType
+ + GetMerchantAccessFlags
+ + Sync
+ + Send,
{
async fn authenticate_and_fetch(
&self,
@@ -1130,6 +1110,8 @@ where
&merchant_id,
request_headers,
profile_id,
+ self.0.get_is_connected_allowed(),
+ self.0.get_is_platform_allowed(),
)
.await?;
Ok((
@@ -1150,6 +1132,8 @@ where
&merchant_id,
request_headers,
profile_id,
+ self.0.get_is_connected_allowed(),
+ self.0.get_is_platform_allowed(),
)
.await?;
Ok((
@@ -1185,6 +1169,7 @@ where
I: AuthenticateAndFetch<AuthenticationData, A>
+ AuthenticateAndFetch<AuthenticationData, A>
+ GetAuthType
+ + GetMerchantAccessFlags
+ Sync
+ Send,
{
@@ -1209,7 +1194,7 @@ where
let auth_data_v2 = AuthenticationData {
merchant_account: auth_data.merchant_account,
- platform_account_with_key_store: None,
+ platform_account_with_key_store: auth_data.platform_account_with_key_store,
key_store: auth_data.key_store,
profile,
};
@@ -1223,6 +1208,8 @@ async fn construct_authentication_data<A>(
merchant_id: &id_type::MerchantId,
request_headers: &HeaderMap,
profile_id: Option<id_type::ProfileId>,
+ is_connected_allowed: bool,
+ is_platform_allowed: bool,
) -> RouterResult<AuthenticationData>
where
A: SessionStateInfo + Sync,
@@ -1237,40 +1224,28 @@ where
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
- let merchant = state
+ let initiator_merchant = state
.store()
.find_merchant_account_by_merchant_id(merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
- // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
- let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
- get_platform_merchant_account(state, request_headers, merchant).await?
- } else {
- (merchant, None)
- };
-
- let platform_account_with_key_store =
- platform_merchant_account
- .clone()
- .map(|platform_account| PlatformAccountWithKeyStore {
- account: platform_account,
- key_store: key_store.clone(),
- });
-
- let key_store = if platform_merchant_account.is_some() {
- state
- .store()
- .get_merchant_key_store_by_merchant_id(
- merchant.get_id(),
- &state.store().get_master_key().to_vec().into(),
- )
- .await
- .change_context(errors::ApiErrorResponse::Unauthorized)
- .attach_printable("Failed to fetch merchant key store for the merchant id")?
- } else {
- key_store
- };
+ // Validate merchant account type access
+ check_merchant_access(
+ state,
+ initiator_merchant.merchant_account_type,
+ is_connected_allowed,
+ is_platform_allowed,
+ )?;
+
+ let (merchant, key_store, platform_account_with_key_store) =
+ resolve_merchant_accounts_and_key_stores(
+ state,
+ request_headers,
+ initiator_merchant,
+ key_store,
+ )
+ .await?;
let auth = AuthenticationData {
merchant_account: merchant,
@@ -2568,54 +2543,34 @@ where
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
- let merchant = state
+ let initiator_merchant = state
.store()
.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
- // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
- let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
- get_platform_merchant_account(state, request_headers, merchant).await?
- } else {
- (merchant, None)
- };
-
- if platform_merchant_account.is_some() && !self.is_platform_allowed {
- return Err(report!(
- errors::ApiErrorResponse::PlatformAccountAuthNotSupported
- ))
- .attach_printable("Platform not authorized to access the resource");
- }
-
- let platform_account_with_key_store =
- platform_merchant_account
- .clone()
- .map(|platform_account| PlatformAccountWithKeyStore {
- account: platform_account,
- key_store: key_store.clone(),
- });
-
- let key_store = if platform_merchant_account.is_some() {
- state
- .store()
- .get_merchant_key_store_by_merchant_id(
- merchant.get_id(),
- &state.store().get_master_key().to_vec().into(),
- )
- .await
- .change_context(errors::ApiErrorResponse::Unauthorized)
- .attach_printable("Failed to fetch merchant key store for the merchant id")?
- } else {
- key_store
- };
-
let profile = state
.store()
.find_business_profile_by_profile_id(&key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
+ check_merchant_access(
+ state,
+ initiator_merchant.merchant_account_type,
+ self.is_connected_allowed,
+ self.is_platform_allowed,
+ )?;
+
+ let (merchant, key_store, platform_account_with_key_store) =
+ resolve_merchant_accounts_and_key_stores(
+ state,
+ request_headers,
+ initiator_merchant.clone(),
+ key_store,
+ )
+ .await?;
+
let auth = AuthenticationData {
merchant_account: merchant,
platform_account_with_key_store,
@@ -2625,7 +2580,7 @@ where
Ok((
auth.clone(),
AuthenticationType::ApiKey {
- merchant_id: auth.merchant_account.get_id().clone(),
+ merchant_id: initiator_merchant.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
@@ -2666,9 +2621,6 @@ where
.attach_printable("Unable to parse client_secret")
})?;
- let key_manager_state: &common_utils::types::keymanager::KeyManagerState =
- &(&state.session_state()).into();
-
let db_client_secret: diesel_models::ClientSecretType = state
.store()
.get_client_secret(client_secret)
@@ -2789,6 +2741,16 @@ impl GetAuthType for PublishableKeyAuth {
}
}
+#[cfg(feature = "partial-auth")]
+impl GetMerchantAccessFlags for PublishableKeyAuth {
+ fn get_is_connected_allowed(&self) -> bool {
+ false // Publishable key doesn't support connected merchant operations currently
+ }
+ fn get_is_platform_allowed(&self) -> bool {
+ false // Publishable key doesn't support platform merchant operations currently
+ }
+}
+
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAuth
@@ -4576,11 +4538,66 @@ where
}
}
-async fn get_connected_merchant_account<A>(
+/// Validates whether the merchant account type is authorized to access the resource
+pub fn check_merchant_access<A>(
+ state: &A,
+ merchant_account_type: MerchantAccountType,
+ is_connected_allowed: bool,
+ is_platform_allowed: bool,
+) -> Result<(), error_stack::Report<errors::ApiErrorResponse>>
+where
+ A: SessionStateInfo + Sync,
+{
+ match merchant_account_type {
+ MerchantAccountType::Connected => {
+ // Check if platform feature is enabled
+ state.conf().platform.enabled.then_some(()).ok_or_else(|| {
+ report!(errors::ApiErrorResponse::ConnectedAccountAuthNotSupported)
+ .attach_printable("Platform feature is not enabled")
+ })?;
+
+ is_connected_allowed.then_some(()).ok_or_else(|| {
+ report!(errors::ApiErrorResponse::ConnectedAccountAuthNotSupported)
+ .attach_printable("Connected Merchant is not authorized to access the resource")
+ })
+ }
+ MerchantAccountType::Platform => {
+ // Check if platform feature is enabled
+ state.conf().platform.enabled.then_some(()).ok_or_else(|| {
+ report!(errors::ApiErrorResponse::PlatformAccountAuthNotSupported)
+ .attach_printable("Platform feature is not enabled")
+ })?;
+
+ // Check if platform is allowed for this resource
+ is_platform_allowed.then_some(()).ok_or_else(|| {
+ report!(errors::ApiErrorResponse::PlatformAccountAuthNotSupported)
+ .attach_printable("Platform Merchant is not authorized to access the resource")
+ })
+ }
+ MerchantAccountType::Standard => Ok(()),
+ }
+}
+
+/// Validates that a merchant account is a valid connected merchant for platform operations
+fn validate_connected_merchant_account(
+ connected_merchant_account: &domain::MerchantAccount,
+ platform_org_id: id_type::OrganizationId,
+) -> RouterResult<()> {
+ (connected_merchant_account.organization_id == platform_org_id
+ && connected_merchant_account.merchant_account_type == MerchantAccountType::Connected)
+ .then_some(())
+ .ok_or_else(|| {
+ report!(errors::ApiErrorResponse::InvalidPlatformOperation)
+ .attach_printable("Invalid connected merchant for platform operation")
+ })
+}
+
+/// Fetches and validates the connected merchant account and key store for platform operations
+async fn get_connected_account_and_key_store<A>(
state: &A,
connected_merchant_id: id_type::MerchantId,
platform_org_id: id_type::OrganizationId,
-) -> RouterResult<domain::MerchantAccount>
+) -> RouterResult<(domain::MerchantAccount, domain::MerchantKeyStore)>
where
A: SessionStateInfo + Sync,
{
@@ -4601,54 +4618,157 @@ where
.to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
- if platform_org_id != connected_merchant_account.organization_id {
- return Err(errors::ApiErrorResponse::InvalidPlatformOperation)
- .attach_printable("Access for merchant id Unauthorized");
- }
+ validate_connected_merchant_account(&connected_merchant_account, platform_org_id)?;
- Ok(connected_merchant_account)
+ Ok((connected_merchant_account, key_store))
}
-async fn get_platform_merchant_account<A>(
+/// Resolves processor and provider merchant accounts
+async fn resolve_merchant_accounts_and_key_stores<A>(
state: &A,
request_headers: &HeaderMap,
- merchant_account: domain::MerchantAccount,
-) -> RouterResult<(domain::MerchantAccount, Option<domain::MerchantAccount>)>
+ initiator_merchant_account: domain::MerchantAccount,
+ merchant_key_store: domain::MerchantKeyStore,
+) -> RouterResult<(
+ domain::MerchantAccount,
+ domain::MerchantKeyStore,
+ Option<PlatformAccountWithKeyStore>,
+)>
where
A: SessionStateInfo + Sync,
{
- let connected_merchant_id =
- get_and_validate_connected_merchant_id(request_headers, &merchant_account)?;
+ let header_map = HeaderMapStruct::new(request_headers);
+
+ let (processor_merchant_account, processor_key_store, platform_account_with_key_store) =
+ match initiator_merchant_account.merchant_account_type {
+ MerchantAccountType::Platform => {
+ let connected_merchant_id = header_map
+ .get_id_type_from_header_if_present::<id_type::MerchantId>(
+ headers::X_CONNECTED_MERCHANT_ID,
+ )?;
+
+ // If header present: platform acts on behalf of connected merchant
+ // If header absent: platform operates on the platform-connected merchant group
+ let (processor_merchant_account, processor_key_store) = match connected_merchant_id
+ {
+ Some(connected_merchant_id) => {
+ get_connected_account_and_key_store(
+ state,
+ connected_merchant_id,
+ initiator_merchant_account.organization_id.clone(),
+ )
+ .await?
+ }
+ None => (
+ initiator_merchant_account.clone(),
+ merchant_key_store.clone(),
+ ),
+ };
- match connected_merchant_id {
- Some(merchant_id) => {
- let connected_merchant_account = get_connected_merchant_account(
- state,
- merchant_id,
- merchant_account.organization_id.clone(),
- )
- .await?;
- Ok((connected_merchant_account, Some(merchant_account)))
- }
- None => Ok((merchant_account, None)),
- }
+ (
+ processor_merchant_account,
+ processor_key_store,
+ Some(PlatformAccountWithKeyStore {
+ account: initiator_merchant_account,
+ key_store: merchant_key_store,
+ }),
+ )
+ }
+ MerchantAccountType::Connected => {
+ fp_utils::when(
+ header_map
+ .get_id_type_from_header_if_present::<id_type::MerchantId>(
+ headers::X_CONNECTED_MERCHANT_ID,
+ )?
+ .is_some(),
+ || {
+ Err(report!(errors::ApiErrorResponse::InvalidConnectedOperation))
+ .attach_printable(
+ "Connected merchant cannot use X-Connected-Merchant-Id header",
+ )
+ },
+ )?;
+
+ let (platform_account, platform_key_store) =
+ get_platform_account_and_key_store(state, &initiator_merchant_account).await?;
+
+ (
+ initiator_merchant_account,
+ merchant_key_store,
+ Some(PlatformAccountWithKeyStore {
+ account: platform_account,
+ key_store: platform_key_store,
+ }),
+ )
+ }
+ MerchantAccountType::Standard => {
+ fp_utils::when(
+ header_map
+ .get_id_type_from_header_if_present::<id_type::MerchantId>(
+ headers::X_CONNECTED_MERCHANT_ID,
+ )?
+ .is_some(),
+ || {
+ Err(report!(errors::ApiErrorResponse::InvalidPlatformOperation))
+ .attach_printable(
+ "Standard merchant cannot use X-Connected-Merchant-Id header",
+ )
+ },
+ )?;
+
+ (initiator_merchant_account, merchant_key_store, None)
+ }
+ };
+ Ok((
+ processor_merchant_account,
+ processor_key_store,
+ platform_account_with_key_store,
+ ))
}
-fn get_and_validate_connected_merchant_id(
- request_headers: &HeaderMap,
+/// Fetches the platform merchant account and key store
+async fn get_platform_account_and_key_store<A>(
+ state: &A,
merchant_account: &domain::MerchantAccount,
-) -> RouterResult<Option<id_type::MerchantId>> {
- HeaderMapStruct::new(request_headers)
- .get_id_type_from_header_if_present::<id_type::MerchantId>(
- headers::X_CONNECTED_MERCHANT_ID,
- )?
- .map(|merchant_id| {
- (merchant_account.is_platform_account())
- .then_some(merchant_id)
- .ok_or(errors::ApiErrorResponse::InvalidPlatformOperation)
+) -> RouterResult<(domain::MerchantAccount, domain::MerchantKeyStore)>
+where
+ A: SessionStateInfo + Sync,
+{
+ let organization = state
+ .session_state()
+ .accounts_store
+ .find_organization_by_org_id(merchant_account.get_org_id())
+ .await
+ .change_context(errors::ApiErrorResponse::InvalidPlatformOperation)
+ .attach_printable("Failed to fetch organization for connected merchant")?;
+
+ let platform_merchant_id = organization.platform_merchant_id.ok_or_else(|| {
+ report!(errors::ApiErrorResponse::InvalidPlatformOperation)
+ .attach_printable("Connected merchant missing platform merchant id")
+ })?;
+
+ let platform_key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ &platform_merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InvalidPlatformOperation)
+ .attach_printable("Failed to fetch key store for platform merchant")?;
+
+ let platform_account = state
+ .store()
+ .find_merchant_account_by_merchant_id(&platform_merchant_id, &platform_key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation)?;
+
+ (platform_account.is_platform_account())
+ .then_some((platform_account, platform_key_store))
+ .ok_or_else(|| {
+ report!(errors::ApiErrorResponse::InvalidPlatformOperation)
+ .attach_printable("Mapped platform merchant is not a platform account")
})
- .transpose()
- .attach_printable("Non platform account using X_CONNECTED_MERCHANT_ID header")
}
fn throw_error_if_platform_merchant_authentication_required(