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(resources): org-scoped, reusable Apple Pay certificate management (#14140)
Shankar Singh C02ba5ea0b4cc
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rsindex 4e864554d0..aed5590c1b 100644--- a/crates/api_models/src/events.rs+++ b/crates/api_models/src/events.rs@@ -34,6 +34,12 @@ use crate::{cards_info::*,disputes::*,files::*,+ hierarchical_resources::{+ GenerateHierarchicalResourceRequest, GenerateHierarchicalResourceResponse,+ HierarchicalResourceSummary, LinkHierarchicalResourceRequest,+ LinkHierarchicalResourceResponse, ListHierarchicalResourcesRequest,+ ListHierarchicalResourcesResponse, UploadCertificateRequest, UploadCertificateResponse,+ },mandates::*,merchant_connector_webhook_management::*,organization::{@@ -149,7 +155,16 @@ impl_api_event_type!(OrganizationUpdateRequest,OrganizationId,CustomerListRequest,- RoutingEventsRequest+ RoutingEventsRequest,+ GenerateHierarchicalResourceRequest,+ GenerateHierarchicalResourceResponse,+ UploadCertificateRequest,+ UploadCertificateResponse,+ HierarchicalResourceSummary,+ ListHierarchicalResourcesRequest,+ ListHierarchicalResourcesResponse,+ LinkHierarchicalResourceRequest,+ LinkHierarchicalResourceResponse));diff --git a/crates/api_models/src/hierarchical_resources.rs b/crates/api_models/src/hierarchical_resources.rsnew file mode 100644index 0000000000..744049e827--- /dev/null+++ b/crates/api_models/src/hierarchical_resources.rs@@ -0,0 +1,68 @@+use common_utils::id_type;+use hyperswitch_masking::Secret;+use time::PrimitiveDateTime;++#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]+#[serde(deny_unknown_fields)]+pub struct GenerateHierarchicalResourceRequest {+ #[serde(rename = "type")]+ pub resource_type: common_enums::ResourceType,+}++#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]+pub struct GenerateHierarchicalResourceResponse {+ pub id: id_type::ResourceId,+ #[schema(value_type = Object)]+ pub data: Secret<serde_json::Value>,+}++#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]+#[serde(deny_unknown_fields)]+pub struct UploadCertificateRequest {+ pub certificate: String,+}++#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]+pub struct UploadCertificateResponse {+ pub id: id_type::ResourceId,+ #[schema(value_type = String)]+ pub created_at: PrimitiveDateTime,+}++#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]+pub struct HierarchicalResourceSummary {+ pub id: id_type::ResourceId,+ #[schema(value_type = Object)]+ pub display_schema: Secret<serde_json::Value>,+ #[schema(value_type = Object)]+ pub display_data: Secret<serde_json::Value>,+ #[schema(value_type = String)]+ pub created_at: PrimitiveDateTime,+ pub is_linked: bool,+}++#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]+#[serde(deny_unknown_fields)]+pub struct ListHierarchicalResourcesRequest {+ #[serde(rename = "type")]+ pub resource_type: common_enums::ResourceType,+ pub scope_id: Option<String>,+ pub scope_type: Option<common_enums::ResourceRequestorType>,+}++#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]+pub struct ListHierarchicalResourcesResponse {+ pub resources: Vec<HierarchicalResourceSummary>,+}++#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]+#[serde(deny_unknown_fields)]+pub struct LinkHierarchicalResourceRequest {+ pub requestor_type: common_enums::ResourceRequestorType,+ pub requestor_id: String,+}++#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)]+pub struct LinkHierarchicalResourceResponse {+ pub id: id_type::ResourceId,+}diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rsindex 76a44504d0..b5df3f787a 100644--- a/crates/api_models/src/lib.rs+++ b/crates/api_models/src/lib.rs@@ -23,6 +23,7 @@ pub mod feature_matrix;pub mod files;pub mod gsm;pub mod health_check;+pub mod hierarchical_resources;pub mod launch_sage;pub mod mandates;pub mod merchant_connector_webhook_management;diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 5bed0dd148..4568f31fe9 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -10,6 +10,7 @@ use std::{pub use accounts::{MerchantAccountRequestType, MerchantAccountType, 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 4fe8c8666d..6c05b5cc75 100644--- a/crates/common_enums/src/enums/accounts.rs+++ b/crates/common_enums/src/enums/accounts.rs@@ -101,3 +101,41 @@ impl From<MerchantAccountRequestType> for MerchantAccountType {}}}++#[derive(+ Clone,+ Copy,+ Debug,+ Eq,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum ResourceRequestorType {+ MerchantConnectorAccount,+ Profile,+ MerchantAccount,+}++#[derive(+ Clone,+ Copy,+ Debug,+ Eq,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum ResourceType {+ ApplePayCertificate,+}diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rsindex 8e6c5d5584..d1373f4554 100644--- a/crates/common_utils/src/id_type.rs+++ b/crates/common_utils/src/id_type.rs@@ -18,6 +18,7 @@ mod profile;mod profile_acquirer;mod refunds;mod relay;+mod resource;mod routing;mod subscription;mod tenant;@@ -61,6 +62,7 @@ pub use self::{profile_acquirer::ProfileAcquirerId,refunds::RefundReferenceId,relay::RelayId,+ resource::ResourceId,routing::RoutingId,subscription::SubscriptionId,tenant::TenantId,diff --git a/crates/common_utils/src/id_type/organization.rs b/crates/common_utils/src/id_type/organization.rsindex b10d6502da..5c4f90c371 100644--- a/crates/common_utils/src/id_type/organization.rs+++ b/crates/common_utils/src/id_type/organization.rs@@ -1,3 +1,5 @@+use error_stack::ResultExt;+use crate::errors::{CustomResult, ValidationError};crate::id_type!(@@ -30,4 +32,13 @@ impl OrganizationId {pub fn get_should_call_pm_modular_service_key(&self) -> String {format!("should_call_pm_modular_service_{}", self.get_string_repr())}++ /// Re-wraps this organization id as a [`super::MerchantId`] for use as an encryption identifier.+ pub fn as_merchant_key_identifier(&self) -> CustomResult<super::MerchantId, ValidationError> {+ super::MerchantId::try_from(std::borrow::Cow::Owned(self.get_string_repr().to_owned()))+ .change_context(ValidationError::InvalidValue {+ message: "organization id could not be used as a merchant key identifier"+ .to_string(),+ })+ }}diff --git a/crates/common_utils/src/id_type/resource.rs b/crates/common_utils/src/id_type/resource.rsnew file mode 100644index 0000000000..b4ecc705eb--- /dev/null+++ b/crates/common_utils/src/id_type/resource.rs@@ -0,0 +1,15 @@+crate::id_type!(+ ResourceId,+ "A type for resource_id that can be used for generic linkable resource ids"+);+crate::impl_id_type_methods!(ResourceId, "resource_id");++// This is to display the `ResourceId` as ResourceId(abcd)+crate::impl_debug_id_type!(ResourceId);+crate::impl_default_id_type!(ResourceId, "res");+crate::impl_try_from_cow_str_id_type!(ResourceId, "resource_id");++crate::impl_generate_id_id_type!(ResourceId, "res");+crate::impl_serializable_secret_id_type!(ResourceId);+crate::impl_queryable_id_type!(ResourceId);+crate::impl_to_sql_from_sql_id_type!(ResourceId);diff --git a/crates/diesel_models/payment_methods_v2.patch b/crates/diesel_models/payment_methods_v2.patchindex a2e0993a79..692b8b2d26 100644--- a/crates/diesel_models/payment_methods_v2.patch+++ b/crates/diesel_models/payment_methods_v2.patch@@ -1,10 +1,7 @@diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs-@@ -1349,14 +1349,79 @@- #[max_length = 64]- profile_id -> Nullable<Varchar>,- #[max_length = 255]+@@ -1323,8 +1323,73 @@secure_link -> Nullable<Varchar>,#[max_length = 64]processor_merchant_id -> Nullable<Varchar>,@@ -78,13 +75,7 @@ diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/sc}}- diesel::table! {- use diesel::sql_types::*;- use crate::enums::diesel_exports::*;-@@ -1917,12 +1982,13 @@- merchant_connector_account,- merchant_key_store,- organization,+@@ -1890,6 +1955,7 @@payment_attempt,payment_intent,payment_link,@@ -92,6 +83,3 @@ diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/scpayout_attempt,payouts,process_tracker,- refund,- relay,- revenue_recovery_retry_stats,diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rsindex c427629fb3..dddeeecbf7 100644--- a/crates/diesel_models/src/business_profile.rs+++ b/crates/diesel_models/src/business_profile.rs@@ -98,6 +98,8 @@ pub struct Profile {pub default_fallback_routing: Option<pii::SecretSerdeValue>,pub surcharge_connector_details: Option<SurchargeConnectorDetails>,pub order_fulfillment_time: Option<i64>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}#[cfg(feature = "v1")]@@ -236,6 +238,8 @@ pub struct ProfileUpdateInternal {pub default_fallback_routing: Option<pii::SecretSerdeValue>,pub surcharge_connector_details: Option<SurchargeConnectorDetails>,pub order_fulfillment_time: Option<i64>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}/// Note: The order of fields in the struct is important.@@ -318,6 +322,8 @@ pub struct Profile {pub default_fallback_routing: Option<pii::SecretSerdeValue>,pub surcharge_connector_details: Option<SurchargeConnectorDetails>,pub order_fulfillment_time: Option<i64>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,pub frm_routing_algorithm_id: Option<String>,@@ -472,6 +478,8 @@ pub struct ProfileUpdateInternal {pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,pub is_l2_l3_enabled: Option<bool>,pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression)]diff --git a/crates/diesel_models/src/hierarchical_resource.rs b/crates/diesel_models/src/hierarchical_resource.rsnew file mode 100644index 0000000000..8289b2603d--- /dev/null+++ b/crates/diesel_models/src/hierarchical_resource.rs@@ -0,0 +1,49 @@+use common_utils::{encryption::Encryption, id_type};+use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};+use hyperswitch_masking::Secret;++use crate::schema::hierarchical_resources;++#[derive(+ Clone,+ Debug,+ Identifiable,+ Queryable,+ Selectable,+ router_derive::DebugAsDisplay,+ serde::Serialize,+ serde::Deserialize,+)]+#[diesel(table_name = hierarchical_resources, primary_key(id), check_for_backend(diesel::pg::Pg))]+pub struct HierarchicalResource {+ pub id: id_type::ResourceId,+ pub resource_type: String,+ pub scope: String,+ pub scope_id: String,+ pub data: Secret<serde_json::Value>,+ pub encrypted_data: Option<Encryption>,+ pub created_by: String,+ pub created_at: time::PrimitiveDateTime,+ pub modified_at: time::PrimitiveDateTime,+}++#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]+#[diesel(table_name = hierarchical_resources)]+pub struct HierarchicalResourceNew {+ pub id: id_type::ResourceId,+ pub resource_type: String,+ pub scope: String,+ pub scope_id: String,+ pub data: Secret<serde_json::Value>,+ pub encrypted_data: Option<Encryption>,+ pub created_by: String,+ pub created_at: time::PrimitiveDateTime,+ pub modified_at: time::PrimitiveDateTime,+}++#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]+#[diesel(table_name = hierarchical_resources)]+pub struct HierarchicalResourceUpdateInternal {+ pub data: Option<Secret<serde_json::Value>>,+ pub modified_at: time::PrimitiveDateTime,+}diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rsindex 2dd2e7fb34..f0c20a541d 100644--- a/crates/diesel_models/src/lib.rs+++ b/crates/diesel_models/src/lib.rs@@ -27,6 +27,7 @@ pub mod file;pub mod fraud_check;pub mod generic_link;pub mod gsm;+pub mod hierarchical_resource;pub mod invoice;#[cfg(feature = "kv_store")]pub mod kv;diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rsindex 03b89fed57..e0f97e5328 100644--- a/crates/diesel_models/src/merchant_account.rs+++ b/crates/diesel_models/src/merchant_account.rs@@ -59,6 +59,8 @@ pub struct MerchantAccount {pub network_tokenization_credentials: Option<Encryption>,pub fingerprint_secret: Option<Secret<String>>,pub offer_engine_config: Option<Encryption>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}#[cfg(feature = "v1")]@@ -138,6 +140,8 @@ impl From<MerchantAccountSetter> for MerchantAccount {network_tokenization_credentials: item.network_tokenization_credentials,fingerprint_secret: item.fingerprint_secret,offer_engine_config: item.offer_engine_config,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,}}}@@ -175,6 +179,8 @@ pub struct MerchantAccount {pub network_tokenization_credentials: Option<Encryption>,pub fingerprint_secret: Option<Secret<String>>,pub offer_engine_config: Option<Encryption>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}#[cfg(feature = "v2")]@@ -198,6 +204,8 @@ impl From<MerchantAccountSetter> for MerchantAccount {network_tokenization_credentials: None, // need to check if we can have this column in v2fingerprint_secret: item.fingerprint_secret,offer_engine_config: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,}}}@@ -311,6 +319,8 @@ pub struct MerchantAccountUpdateInternal {pub recon_status: Option<storage_enums::ReconStatus>,pub is_platform_account: Option<bool>,pub product_type: Option<common_enums::MerchantProductType>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}#[cfg(feature = "v1")]@@ -347,4 +357,6 @@ pub struct MerchantAccountUpdateInternal {pub product_type: Option<common_enums::MerchantProductType>,pub network_tokenization_credentials: Option<Encryption>,pub offer_engine_config: Option<Encryption>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rsindex 3fbf42c04f..d89b08ca25 100644--- a/crates/diesel_models/src/merchant_connector_account.rs+++ b/crates/diesel_models/src/merchant_connector_account.rs@@ -56,6 +56,8 @@ pub struct MerchantConnectorAccount {pub version: common_enums::ApiVersion,pub id: Option<id_type::MerchantConnectorAccountId>,pub connector_webhook_registration_details: Option<serde_json::Value>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}#[cfg(feature = "v1")]@@ -107,6 +109,8 @@ pub struct MerchantConnectorAccount {pub id: id_type::MerchantConnectorAccountId,#[serde(default)]pub connector_webhook_registration_details: Option<serde_json::Value>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,}@@ -206,6 +210,8 @@ pub struct MerchantConnectorAccountUpdateInternal {pub connector_wallets_details: Option<Encryption>,pub additional_merchant_data: Option<Encryption>,pub connector_webhook_registration_details: Option<serde_json::Value>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}#[cfg(feature = "v2")]@@ -230,6 +236,8 @@ pub struct MerchantConnectorAccountUpdateInternal {pub connector_wallets_details: Option<Encryption>,pub additional_merchant_data: Option<Encryption>,pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: Option<Encryption>,}#[cfg(feature = "v1")]diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rsindex adb54efee1..bd7122e613 100644--- a/crates/diesel_models/src/query.rs+++ b/crates/diesel_models/src/query.rs@@ -25,6 +25,7 @@ pub mod fraud_check;pub mod generic_link;pub mod generics;pub mod gsm;+pub mod hierarchical_resource;pub mod invoice;pub mod locker_mock_up;pub mod mandate;diff --git a/crates/diesel_models/src/query/hierarchical_resource.rs b/crates/diesel_models/src/query/hierarchical_resource.rsnew file mode 100644index 0000000000..a23f547830--- /dev/null+++ b/crates/diesel_models/src/query/hierarchical_resource.rs@@ -0,0 +1,59 @@+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};++use crate::{+ hierarchical_resource::{+ HierarchicalResource, HierarchicalResourceNew, HierarchicalResourceUpdateInternal,+ },+ query::generics,+ schema::hierarchical_resources::dsl,+ DatabaseConnectionWithContext, StorageResult,+};++impl HierarchicalResourceNew {+ pub async fn insert(+ self,+ conn: &DatabaseConnectionWithContext<'_>,+ ) -> StorageResult<HierarchicalResource> {+ generics::generic_insert(conn, self).await+ }+}++impl HierarchicalResource {+ pub async fn find_by_id(+ conn: &DatabaseConnectionWithContext<'_>,+ id: common_utils::id_type::ResourceId,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, dsl::id.eq(id)).await+ }++ pub async fn list_by_scope_id_and_resource_type(+ conn: &DatabaseConnectionWithContext<'_>,+ scope_id: String,+ resource_type: String,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ dsl::scope_id+ .eq(scope_id)+ .and(dsl::resource_type.eq(resource_type)),+ None,+ None,+ Some(dsl::created_at.asc()),+ )+ .await+ }++ pub async fn update_by_id(+ conn: &DatabaseConnectionWithContext<'_>,+ id: common_utils::id_type::ResourceId,+ update: HierarchicalResourceUpdateInternal,+ ) -> StorageResult<Self> {+ generics::generic_update_with_unique_predicate_get_result::<+ <Self as HasTable>::Table,+ _,+ _,+ _,+ >(conn, dsl::id.eq(id), update)+ .await+ }+}diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rsindex 984407cf02..4aafd38cc0 100644--- a/crates/diesel_models/src/query/utils.rs+++ b/crates/diesel_models/src/query/utils.rs@@ -105,6 +105,7 @@ impl_get_primary_key!(schema::invoice::table,schema::subscription::table,schema::batch_blocklist_jobs::table,+ schema::hierarchical_resources::table,// v2 tablesschema_v2::dashboard_metadata::table,schema_v2::merchant_connector_account::table,diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 36d9cc352d..6a596f3702 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -341,6 +341,8 @@ diesel::table! {default_fallback_routing -> Nullable<Jsonb>,surcharge_connector_details -> Nullable<Jsonb>,order_fulfillment_time -> Nullable<Int8>,+ apple_pay_certificates -> Nullable<Jsonb>,+ apple_pay_certificates_encrypted -> Nullable<Bytea>,}}@@ -792,6 +794,27 @@ diesel::table! {}}+diesel::table! {+ use diesel::sql_types::*;+ use crate::enums::diesel_exports::*;++ hierarchical_resources (id) {+ #[max_length = 64]+ id -> Varchar,+ #[max_length = 64]+ resource_type -> Varchar,+ #[max_length = 32]+ scope -> Varchar,+ #[max_length = 64]+ scope_id -> Varchar,+ data -> Jsonb,+ encrypted_data -> Nullable<Bytea>,+ created_by -> Text,+ created_at -> Timestamp,+ modified_at -> Timestamp,+ }+}+diesel::table! {use diesel::sql_types::*;use crate::enums::diesel_exports::*;@@ -992,6 +1015,8 @@ diesel::table! {#[max_length = 128]fingerprint_secret -> Nullable<Varchar>,offer_engine_config -> Nullable<Bytea>,+ apple_pay_certificates -> Nullable<Jsonb>,+ apple_pay_certificates_encrypted -> Nullable<Bytea>,}}@@ -1035,6 +1060,8 @@ diesel::table! {#[max_length = 64]id -> Nullable<Varchar>,connector_webhook_registration_details -> Nullable<Jsonb>,+ apple_pay_certificates -> Nullable<Jsonb>,+ apple_pay_certificates_encrypted -> Nullable<Bytea>,}}@@ -1983,6 +2010,7 @@ diesel::allow_tables_to_appear_in_same_query!(fraud_check,gateway_status_map,generic_link,+ hierarchical_resources,incremental_authorization,invoice,locker_mock_up,diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex d30076ac82..5d1f2599f6 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -315,6 +315,8 @@ diesel::table! {default_fallback_routing -> Nullable<Jsonb>,surcharge_connector_details -> Nullable<Jsonb>,order_fulfillment_time -> Nullable<Int8>,+ apple_pay_certificates -> Nullable<Jsonb>,+ apple_pay_certificates_encrypted -> Nullable<Bytea>,#[max_length = 64]routing_algorithm_id -> Nullable<Varchar>,order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>,@@ -781,6 +783,27 @@ diesel::table! {}}+diesel::table! {+ use diesel::sql_types::*;+ use crate::enums::diesel_exports::*;++ hierarchical_resources (id) {+ #[max_length = 64]+ id -> Varchar,+ #[max_length = 64]+ resource_type -> Varchar,+ #[max_length = 32]+ scope -> Varchar,+ #[max_length = 64]+ scope_id -> Varchar,+ data -> Jsonb,+ encrypted_data -> Nullable<Bytea>,+ created_by -> Text,+ created_at -> Timestamp,+ modified_at -> Timestamp,+ }+}+diesel::table! {use diesel::sql_types::*;use crate::enums::diesel_exports::*;@@ -958,6 +981,8 @@ diesel::table! {#[max_length = 128]fingerprint_secret -> Nullable<Varchar>,offer_engine_config -> Nullable<Bytea>,+ apple_pay_certificates -> Nullable<Jsonb>,+ apple_pay_certificates_encrypted -> Nullable<Bytea>,}}@@ -992,6 +1017,8 @@ diesel::table! {#[max_length = 64]id -> Varchar,connector_webhook_registration_details -> Nullable<Jsonb>,+ apple_pay_certificates -> Nullable<Jsonb>,+ apple_pay_certificates_encrypted -> Nullable<Bytea>,feature_metadata -> Nullable<Jsonb>,}}@@ -1924,6 +1951,7 @@ diesel::allow_tables_to_appear_in_same_query!(fraud_check,gateway_status_map,generic_link,+ hierarchical_resources,incremental_authorization,invoice,locker_mock_up,diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rsindex 974c504406..ecb21de84c 100644--- a/crates/hyperswitch_domain_models/src/business_profile.rs+++ b/crates/hyperswitch_domain_models/src/business_profile.rs@@ -93,6 +93,8 @@ pub struct Profile {pub network_tokenization_credentials: OptionalEncryptableValue,pub payment_method_blocking: Option<PaymentMethodBlockingConfig>,pub default_fallback_routing: Option<pii::SecretSerdeValue>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: OptionalEncryptableValue,}#[cfg(feature = "v1")]@@ -346,6 +348,8 @@ impl From<ProfileSetter> for Profile {network_tokenization_credentials: value.network_tokenization_credentials,payment_method_blocking: value.payment_method_blocking,default_fallback_routing: value.default_fallback_routing,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,}}}@@ -416,6 +420,8 @@ pub struct ProfileDbBuilder {pub network_tokenization_credentials: OptionalEncryptableValue,pub payment_method_blocking: Option<PaymentMethodBlockingConfig>,pub default_fallback_routing: Option<pii::SecretSerdeValue>,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: OptionalEncryptableValue,}#[cfg(feature = "v1")]@@ -488,6 +494,8 @@ impl From<ProfileDbBuilder> for Profile {network_tokenization_credentials: value.network_tokenization_credentials,payment_method_blocking: value.payment_method_blocking,default_fallback_routing: value.default_fallback_routing,+ apple_pay_certificates: value.apple_pay_certificates,+ apple_pay_certificates_encrypted: value.apple_pay_certificates_encrypted,}}}@@ -595,6 +603,10 @@ pub enum ProfileUpdate {DefaultRoutingFallbackUpdate {default_fallback_routing: Option<pii::SecretSerdeValue>,},+ ApplePayCertificateCacheUpdate {+ apple_pay_certificates: Option<serde_json::Value>,+ apple_pay_certificates_encrypted: Option<common_utils::encryption::Encryption>,+ },}#[cfg(feature = "v2")]@@ -1324,6 +1336,10 @@ pub enum ProfileUpdate {revenue_recovery_retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType,revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,},+ ApplePayCertificateCacheUpdate {+ apple_pay_certificates: Option<serde_json::Value>,+ apple_pay_certificates_encrypted: Option<common_utils::encryption::Encryption>,+ },}#[async_trait::async_trait]diff --git a/crates/hyperswitch_domain_models/src/hierarchical_resource.rs b/crates/hyperswitch_domain_models/src/hierarchical_resource.rsnew file mode 100644index 0000000000..ba61fcb86a--- /dev/null+++ b/crates/hyperswitch_domain_models/src/hierarchical_resource.rs@@ -0,0 +1,174 @@+use common_utils::{+ crypto::Encryptable,+ custom_serde, date_time,+ errors::{CustomResult, ValidationError},+ id_type,+ types::keymanager::{self, KeyManagerState},+};+use error_stack::ResultExt;+use hyperswitch_masking::{PeekInterface, Secret};+use time::PrimitiveDateTime;++use crate::type_encryption::{crypto_operation, CryptoOperation};++#[derive(Clone, Debug, serde::Serialize)]+pub struct HierarchicalResource {+ pub id: id_type::ResourceId,+ pub resource_type: String,+ pub scope: String,+ pub scope_id: String,+ pub data: Secret<serde_json::Value>,+ pub encrypted_data: Option<Encryptable<Secret<String>>>,+ pub created_by: String,+ #[serde(with = "custom_serde::iso8601")]+ pub created_at: PrimitiveDateTime,+ #[serde(with = "custom_serde::iso8601")]+ pub modified_at: PrimitiveDateTime,+}++fn key_identifier_from_scope_id(+ scope_id: &str,+) -> CustomResult<keymanager::Identifier, ValidationError> {+ let organization_id = id_type::OrganizationId::try_from_string(scope_id.to_owned())?;+ Ok(keymanager::Identifier::Merchant(+ organization_id.as_merchant_key_identifier()?,+ ))+}++impl HierarchicalResource {+ pub fn key_identifier(&self) -> CustomResult<keymanager::Identifier, ValidationError> {+ key_identifier_from_scope_id(&self.scope_id)+ }++ pub fn identifier_for_diesel(+ item: &diesel_models::hierarchical_resource::HierarchicalResource,+ ) -> CustomResult<keymanager::Identifier, ValidationError> {+ key_identifier_from_scope_id(&item.scope_id)+ }+}++#[async_trait::async_trait]+impl super::behaviour::Conversion for HierarchicalResource {+ type DstType = diesel_models::hierarchical_resource::HierarchicalResource;+ type NewDstType = diesel_models::hierarchical_resource::HierarchicalResourceNew;++ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {+ Ok(diesel_models::hierarchical_resource::HierarchicalResource {+ id: self.id,+ resource_type: self.resource_type,+ scope: self.scope,+ scope_id: self.scope_id,+ data: self.data,+ encrypted_data: self.encrypted_data.map(Encryptable::into),+ created_by: self.created_by,+ created_at: self.created_at,+ modified_at: self.modified_at,+ })+ }++ async fn convert_back(+ state: &KeyManagerState,+ item: Self::DstType,+ key: &Secret<Vec<u8>>,+ _key_manager_identifier: keymanager::Identifier,+ ) -> CustomResult<Self, ValidationError>+ where+ Self: Sized,+ {+ let organization_id = id_type::OrganizationId::try_from_string(item.scope_id.clone())?;+ let identifier =+ keymanager::Identifier::Merchant(organization_id.as_merchant_key_identifier()?);++ let encrypted_data = crypto_operation(+ state,+ common_utils::type_name!(Self::DstType),+ CryptoOperation::DecryptOptional(item.encrypted_data),+ identifier,+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting resource".to_string(),+ })?;++ Ok(Self {+ id: item.id,+ resource_type: item.resource_type,+ scope: item.scope,+ scope_id: item.scope_id,+ data: item.data,+ encrypted_data,+ created_by: item.created_by,+ created_at: item.created_at,+ modified_at: item.modified_at,+ })+ }++ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {+ Ok(+ diesel_models::hierarchical_resource::HierarchicalResourceNew {+ id: self.id,+ resource_type: self.resource_type,+ scope: self.scope,+ scope_id: self.scope_id,+ data: self.data,+ encrypted_data: self.encrypted_data.map(Encryptable::into),+ created_by: self.created_by,+ created_at: date_time::now(),+ modified_at: date_time::now(),+ },+ )+ }+}++pub struct HierarchicalResourceDataUpdate {+ pub data: Secret<serde_json::Value>,+}++impl From<HierarchicalResourceDataUpdate>+ for diesel_models::hierarchical_resource::HierarchicalResourceUpdateInternal+{+ fn from(value: HierarchicalResourceDataUpdate) -> Self {+ Self {+ data: Some(value.data),+ modified_at: date_time::now(),+ }+ }+}++#[async_trait::async_trait]+pub trait HierarchicalResourceInterface {+ type Error;++ async fn insert_linked_resource(+ &self,+ resource: HierarchicalResource,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<HierarchicalResource, Self::Error>;++ async fn find_linked_resource_by_id(+ &self,+ id: id_type::ResourceId,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<HierarchicalResource, Self::Error>;++ async fn find_resource_scope_id(+ &self,+ id: id_type::ResourceId,+ ) -> CustomResult<String, Self::Error>;++ async fn list_linked_resources_by_scope_id_and_resource_type(+ &self,+ scope_id: String,+ resource_type: String,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<Vec<HierarchicalResource>, Self::Error>;++ async fn update_linked_resource_data(+ &self,+ id: id_type::ResourceId,+ update: HierarchicalResourceDataUpdate,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<HierarchicalResource, Self::Error>;+}diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rsindex 1bff3fe974..9aa3f54abf 100644--- a/crates/hyperswitch_domain_models/src/lib.rs+++ b/crates/hyperswitch_domain_models/src/lib.rs@@ -16,6 +16,7 @@ pub mod disputes;pub mod errors;pub mod ext_traits;pub mod gsm;+pub mod hierarchical_resource;pub mod invoice;pub mod mandates;pub mod master_key;diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rsindex 56d0c6e5ce..5605aaa2ef 100644--- a/crates/hyperswitch_domain_models/src/merchant_account.rs+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs@@ -1,5 +1,6 @@use common_utils::{crypto::{OptionalEncryptableName, OptionalEncryptableValue},+ encryption::Encryption,errors::CustomResult,ext_traits::ValueExt,pii,@@ -47,6 +48,8 @@ pub struct MerchantAccount {pub network_tokenization_credentials: OptionalEncryptableValue,pub fingerprint_secret: Option<Secret<String>>,pub offer_engine_config: OptionalEncryptableValue,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: OptionalEncryptableValue,}#[cfg(feature = "v1")]@@ -87,6 +90,8 @@ pub struct MerchantAccountSetter {pub network_tokenization_credentials: OptionalEncryptableValue,pub fingerprint_secret: Option<Secret<String>>,pub offer_engine_config: OptionalEncryptableValue,+ pub apple_pay_certificates: Option<serde_json::Value>,+ pub apple_pay_certificates_encrypted: OptionalEncryptableValue,}#[cfg(feature = "v1")]@@ -127,6 +132,8 @@ impl From<MerchantAccountSetter> for MerchantAccount {network_tokenization_credentials: item.network_tokenization_credentials,fingerprint_secret: item.fingerprint_secret,offer_engine_config: item.offer_engine_config,+ apple_pay_certificates: item.apple_pay_certificates,+ apple_pay_certificates_encrypted: item.apple_pay_certificates_encrypted,}}}@@ -305,6 +312,10 @@ pub enum MerchantAccountUpdate {},UnsetDefaultProfile,ModifiedAtUpdate,+ ApplePayCertificateCacheUpdate {+ apple_pay_certificates: Option<serde_json::Value>,+ apple_pay_certificates_encrypted: Option<Encryption>,+ },}#[cfg(feature = "v2")]@@ -323,6 +334,10 @@ pub enum MerchantAccountUpdate {recon_status: diesel_models::enums::ReconStatus,},ModifiedAtUpdate,+ ApplePayCertificateCacheUpdate {+ apple_pay_certificates: Option<serde_json::Value>,+ apple_pay_certificates_encrypted: Option<Encryption>,+ },}impl MerchantAccount {diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rsindex 183e05ca77..d915ee6fdc 100644--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs@@ -69,6 +69,9 @@ pub struct MerchantConnectorAccount {pub additional_merchant_data: Option<Encryptable<Secret<Value>>>,pub version: common_enums::ApiVersion,pub connector_webhook_registration_details: Option<Value>,+ pub apple_pay_certificates: Option<Value>,+ #[encrypt]+ pub apple_pay_certificates_encrypted: Option<Encryptable<Secret<Value>>>,}#[cfg(feature = "v1")]@@ -527,6 +530,10 @@ pub enum MerchantConnectorAccountUpdate {connector_webhook_details: Option<pii::SecretSerdeValue>,metadata: Option<pii::SecretSerdeValue>,},+ ApplePayCertificateCacheUpdate {+ apple_pay_certificates: Option<Value>,+ apple_pay_certificates_encrypted: Option<Encryption>,+ },}#[cfg(feature = "v2")]@@ -551,6 +558,10 @@ pub enum MerchantConnectorAccountUpdate {ConnectorWalletDetailsUpdate {connector_wallets_details: Encryptable<pii::SecretSerdeValue>,},+ ApplePayCertificateCacheUpdate {+ apple_pay_certificates: Option<Value>,+ apple_pay_certificates_encrypted: Option<Encryption>,+ },}#[cfg(feature = "v1")]@@ -588,6 +599,10 @@ impl behaviour::Conversion for MerchantConnectorAccount {additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),version: self.version,connector_webhook_registration_details: self.connector_webhook_registration_details,+ apple_pay_certificates: self.apple_pay_certificates,+ apple_pay_certificates_encrypted: self+ .apple_pay_certificates_encrypted+ .map(|data| data.into()),})}@@ -606,6 +621,7 @@ impl behaviour::Conversion for MerchantConnectorAccount {connector_account_details: other.connector_account_details,additional_merchant_data: other.additional_merchant_data,connector_wallets_details: other.connector_wallets_details,+ apple_pay_certificates_encrypted: other.apple_pay_certificates_encrypted,},)),identifier.clone(),@@ -653,6 +669,8 @@ impl behaviour::Conversion for MerchantConnectorAccount {additional_merchant_data: decrypted_data.additional_merchant_data,version: other.version,connector_webhook_registration_details: other.connector_webhook_registration_details,+ apple_pay_certificates: other.apple_pay_certificates,+ apple_pay_certificates_encrypted: decrypted_data.apple_pay_certificates_encrypted,})}@@ -719,6 +737,8 @@ impl behaviour::Conversion for MerchantConnectorAccount {version: self.version,feature_metadata: self.feature_metadata.map(From::from),connector_webhook_registration_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,})}@@ -849,6 +869,8 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInteconnector_wallets_details: connector_wallets_details.map(Encryption::from),additional_merchant_data: additional_merchant_data.map(Encryption::from),connector_webhook_registration_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {connector_wallets_details,@@ -872,6 +894,8 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateIntestatus: None,additional_merchant_data: None,connector_webhook_registration_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},MerchantConnectorAccountUpdate::ConnectorWebhookRegisterationUpdate {connector_webhook_registration_details,@@ -897,6 +921,34 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInteconnector_wallets_details: None,additional_merchant_data: None,connector_webhook_registration_details,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,+ },+ MerchantConnectorAccountUpdate::ApplePayCertificateCacheUpdate {+ apple_pay_certificates,+ apple_pay_certificates_encrypted,+ } => Self {+ connector_type: None,+ connector_name: None,+ connector_account_details: None,+ connector_label: None,+ test_mode: None,+ disabled: None,+ merchant_connector_id: None,+ payment_methods_enabled: None,+ frm_configs: None,+ metadata: None,+ modified_at: Some(date_time::now()),+ connector_webhook_details: None,+ frm_config: None,+ applepay_verified_domains: None,+ pm_auth_config: None,+ status: None,+ connector_wallets_details: None,+ additional_merchant_data: None,+ connector_webhook_registration_details: None,+ apple_pay_certificates,+ apple_pay_certificates_encrypted,},}}@@ -937,6 +989,8 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInteconnector_wallets_details: connector_wallets_details.map(Encryption::from),additional_merchant_data: additional_merchant_data.map(Encryption::from),feature_metadata: feature_metadata.map(From::from),+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {connector_wallets_details,@@ -956,6 +1010,30 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateIntestatus: None,additional_merchant_data: None,feature_metadata: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,+ },+ MerchantConnectorAccountUpdate::ApplePayCertificateCacheUpdate {+ apple_pay_certificates,+ apple_pay_certificates_encrypted,+ } => Self {+ connector_type: None,+ connector_account_details: None,+ connector_label: None,+ disabled: None,+ payment_methods_enabled: None,+ metadata: None,+ modified_at: Some(date_time::now()),+ connector_webhook_details: None,+ frm_config: None,+ applepay_verified_domains: None,+ pm_auth_config: None,+ status: None,+ connector_wallets_details: None,+ additional_merchant_data: None,+ feature_metadata: None,+ apple_pay_certificates,+ apple_pay_certificates_encrypted,},}}diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rsindex 83986c4636..41e913d2c2 100644--- a/crates/hyperswitch_interfaces/src/configs.rs+++ b/crates/hyperswitch_interfaces/src/configs.rs@@ -149,6 +149,32 @@ impl MerchantConnectorAccountType {None}+ #[cfg(feature = "v1")]+ pub fn get_apple_pay_certificate_cache(+ &self,+ ) -> Option<(+ serde_json::Value,+ common_utils::crypto::OptionalEncryptableValue,+ )> {+ match self {+ Self::DbVal(val) => val+ .apple_pay_certificates+ .clone()+ .map(|data| (data, val.apple_pay_certificates_encrypted.clone())),+ Self::CacheVal(_) => None,+ }+ }++ #[cfg(feature = "v2")]+ pub fn get_apple_pay_certificate_cache(+ &self,+ ) -> Option<(+ serde_json::Value,+ common_utils::crypto::OptionalEncryptableValue,+ )> {+ None+ }+pub fn get_merchant_id(&self) -> Option<id_type::MerchantId> {match self {Self::DbVal(db_val) => Some(db_val.merchant_id.clone()),diff --git a/crates/router/src/core.rs b/crates/router/src/core.rsindex 30abd44146..41ab5c7f5b 100644--- a/crates/router/src/core.rs+++ b/crates/router/src/core.rs@@ -46,6 +46,7 @@ pub mod payments;#[cfg(feature = "v2")]pub mod split_payments;+pub mod hierarchical_resources;#[cfg(feature = "payouts")]pub mod payout_link;#[cfg(feature = "payouts")]diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex 7cf9d74c95..97ce11d60b 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -643,6 +643,8 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {"fs",))),offer_engine_config: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},)}@@ -2264,6 +2266,7 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect).await?,additional_merchant_data: merchant_recipient_data.map(Secret::new),+ apple_pay_certificates_encrypted: None,},),),@@ -2612,6 +2615,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {).await?,additional_merchant_data: merchant_recipient_data.map(Secret::new),+ apple_pay_certificates_encrypted: None,},),),@@ -2664,6 +2668,8 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {additional_merchant_data: encrypted_data.additional_merchant_data,version: common_types::consts::API_VERSION,connector_webhook_registration_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,})}diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rsindex 87b42ce905..6f43fc7f09 100644--- a/crates/router/src/core/fraud_check.rs+++ b/crates/router/src/core/fraud_check.rs@@ -101,6 +101,26 @@ where).await?;+ use common_utils::ext_traits::OptionExt;++ let profile_id = payment_data+ .get_payment_intent()+ .profile_id+ .as_ref()+ .get_required_value("profile_id")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("profile_id is not set in payment_intent")?;+ let business_profile = state+ .store+ .find_business_profile_by_merchant_id_profile_id(+ platform.get_processor().get_key_store(),+ platform.get_processor().get_account().get_id(),+ profile_id,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch business profile for FRM router data construction")?;+frm_data.payment_attempt.connector_transaction_id@@ -111,6 +131,7 @@ wherestate,&frm_data.connector_details.connector_name,platform.get_processor(),+ &business_profile,&merchant_connector_account,None,None,diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rsindex 5d643f195a..3d0e96e80a 100644--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs@@ -48,6 +48,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudCstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ _business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,_merchant_recipient_data: Option<MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rsindex 2d9a42d4e6..3cf2c2098d 100644--- a/crates/router/src/core/fraud_check/flows/record_return.rs+++ b/crates/router/src/core/fraud_check/flows/record_return.rs@@ -47,6 +47,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudChstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ _business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,_merchant_recipient_data: Option<MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rsindex 6c555c996c..98455a01e6 100644--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs@@ -45,6 +45,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckRespstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ _business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,_merchant_recipient_data: Option<MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rsindex 382913468c..ff7ac0a838 100644--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs@@ -51,6 +51,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ _business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,_merchant_recipient_data: Option<MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,diff --git a/crates/router/src/core/hierarchical_resources.rs b/crates/router/src/core/hierarchical_resources.rsnew file mode 100644index 0000000000..2de2103699--- /dev/null+++ b/crates/router/src/core/hierarchical_resources.rs@@ -0,0 +1,945 @@+use api_models::hierarchical_resources as api_resources;+use async_trait::async_trait;+use base64::Engine;+use common_utils::{+ date_time, id_type,+ types::keymanager::{self as km_types, EncryptionTransferRequest, KeyManagerState},+};+use error_stack::{report, ResultExt};+use hyperswitch_masking::{PeekInterface, Secret};+use openssl::{+ ec::{EcGroup, EcKey},+ nid::Nid,+ pkey::PKey,+ x509::{X509NameBuilder, X509Req, X509},+};++use crate::{+ core::errors::{self, RouterResponse, RouterResult, StorageErrorExt},+ db::StorageInterface,+ routes::SessionState,+ services::api::ApplicationResponse,+ types::domain,+};++const RESOURCE_SCOPE_ORGANIZATION: &str = "organization";++#[async_trait]+trait HierarchicalResourceHandler {+ async fn generate(+ state: &SessionState,+ processor: &domain::Processor,+ org_key_store: &domain::MerchantKeyStore,+ ) -> RouterResult<(+ domain::HierarchicalResource,+ api_resources::GenerateHierarchicalResourceResponse,+ )>;++ fn display_schema() -> Secret<serde_json::Value>;++ fn display_data(+ resource: &domain::HierarchicalResource,+ ) -> RouterResult<Secret<serde_json::Value>>;++ fn is_linkable(resource: &domain::HierarchicalResource) -> RouterResult<bool>;++ async fn on_link(+ state: &SessionState,+ key_manager_state: &KeyManagerState,+ resource: &domain::HierarchicalResource,+ resource_id: &id_type::ResourceId,+ account: RequestorAccount,+ account_key_store: &domain::MerchantKeyStore,+ ) -> RouterResult<()>;+}++#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+enum ApplePayCertificateStatus {+ CsrGenerated,+ Active,+ Failed,+}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+struct ApplePayCertificateData {+ status: ApplePayCertificateStatus,+ #[serde(skip_serializing_if = "Option::is_none")]+ apple_pay_merchant_identifier: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ payment_processing_certificate: Option<String>,+}++#[derive(Debug, Clone, serde::Serialize)]+struct ApplePayCertificateCachePayload {+ resource_id: id_type::ResourceId,+ data: ApplePayCertificateCacheData,+}++#[derive(Debug, Clone, serde::Serialize)]+struct ApplePayCertificateCacheData {+ merchant_identifier: Option<String>,+ payment_processing_certificate: Option<String>,+}++#[derive(Debug, Clone, serde::Serialize)]+struct ApplePayCertificateKeyWrapper {+ data: ApplePayCertificateKeyWrapperData,+}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+struct ApplePayCertificateKeyWrapperData {+ payment_processing_certificate_key: Secret<String>,+}++#[derive(Debug, Clone, serde::Serialize)]+struct ApplePayCertificateCsrData {+ csr: String,+}++#[derive(Debug, Clone, serde::Serialize)]+struct ApplePayCertificateDisplaySchema {+ apple_pay_merchant_identifier: &'static str,+}++impl Default for ApplePayCertificateDisplaySchema {+ fn default() -> Self {+ Self {+ apple_pay_merchant_identifier: "String",+ }+ }+}++#[derive(Debug, Clone, serde::Serialize)]+struct ApplePayCertificateDisplayData {+ apple_pay_merchant_identifier: Option<String>,+}++fn parse_apple_pay_certificate_data(+ resource_data: &Secret<serde_json::Value>,+) -> RouterResult<ApplePayCertificateData> {+ serde_json::from_value(resource_data.peek().clone())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse Apple Pay certificate resource data")+}++struct ApplePayCertificateResource;++#[async_trait]+impl HierarchicalResourceHandler for ApplePayCertificateResource {+ async fn generate(+ state: &SessionState,+ processor: &domain::Processor,+ org_key_store: &domain::MerchantKeyStore,+ ) -> RouterResult<(+ domain::HierarchicalResource,+ api_resources::GenerateHierarchicalResourceResponse,+ )> {+ let key_manager_state: &KeyManagerState = &state.into();+ let merchant_account = processor.get_account();+ let created_by = format!("merchant:{}", merchant_account.get_id().get_string_repr());+ let organization_id = merchant_account.organization_id.clone();++ let (private_key_pem, csr_pem) = generate_ec_keypair_and_csr()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to generate Apple Pay EC keypair/CSR")?;++ let identifier = km_types::Identifier::Merchant(+ organization_id+ .as_merchant_key_identifier()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to derive organization key identifier")?,+ );++ let private_key_payload = serde_json::to_string(&ApplePayCertificateKeyWrapperData {+ payment_processing_certificate_key: private_key_pem,+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize Apple Pay private key payload")?;++ let encrypted_private_key = domain::types::crypto_operation(+ key_manager_state,+ common_utils::type_name!(domain::HierarchicalResource),+ domain::types::CryptoOperation::Encrypt(Secret::new(private_key_payload)),+ identifier,+ org_key_store.key.peek(),+ )+ .await+ .and_then(|value| value.try_into_operation())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encrypt generated Apple Pay private key")?;++ let data = ApplePayCertificateData {+ status: ApplePayCertificateStatus::CsrGenerated,+ apple_pay_merchant_identifier: None,+ payment_processing_certificate: None,+ };++ let resource_id = id_type::ResourceId::default();+ let resource = domain::HierarchicalResource {+ id: resource_id.clone(),+ resource_type: common_enums::ResourceType::ApplePayCertificate.to_string(),+ scope: RESOURCE_SCOPE_ORGANIZATION.to_string(),+ scope_id: organization_id.get_string_repr().to_string(),+ data: Secret::new(+ serde_json::to_value(&data)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize Apple Pay certificate resource data")?,+ ),+ encrypted_data: Some(encrypted_private_key),+ created_by,+ created_at: date_time::now(),+ modified_at: date_time::now(),+ };++ let csr_data = serde_json::to_value(ApplePayCertificateCsrData { csr: csr_pem })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize Apple Pay CSR response data")?;++ let response_data = serde_json::Map::from_iter([(+ common_enums::ResourceType::ApplePayCertificate.to_string(),+ csr_data,+ )]);++ Ok((+ resource,+ api_resources::GenerateHierarchicalResourceResponse {+ id: resource_id,+ data: Secret::new(serde_json::Value::Object(response_data)),+ },+ ))+ }++ fn display_schema() -> Secret<serde_json::Value> {+ Secret::new(+ serde_json::to_value(ApplePayCertificateDisplaySchema::default())+ .unwrap_or(serde_json::Value::Null),+ )+ }++ fn display_data(+ resource: &domain::HierarchicalResource,+ ) -> RouterResult<Secret<serde_json::Value>> {+ let data = parse_apple_pay_certificate_data(&resource.data)?;+ serde_json::to_value(ApplePayCertificateDisplayData {+ apple_pay_merchant_identifier: data.apple_pay_merchant_identifier,+ })+ .map(Secret::new)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize Apple Pay certificate display data")+ }++ fn is_linkable(resource: &domain::HierarchicalResource) -> RouterResult<bool> {+ let data = parse_apple_pay_certificate_data(&resource.data)?;+ Ok(data.status == ApplePayCertificateStatus::Active)+ }++ async fn on_link(+ state: &SessionState,+ key_manager_state: &KeyManagerState,+ resource: &domain::HierarchicalResource,+ resource_id: &id_type::ResourceId,+ account: RequestorAccount,+ account_key_store: &domain::MerchantKeyStore,+ ) -> RouterResult<()> {+ let db = state.store.as_ref();++ match resource.encrypted_data.as_ref() {+ Some(private_key) => {+ let data = parse_apple_pay_certificate_data(&resource.data)?;++ let plain_data = serde_json::to_value(ApplePayCertificateCachePayload {+ resource_id: resource_id.clone(),+ data: ApplePayCertificateCacheData {+ merchant_identifier: data.apple_pay_merchant_identifier,+ payment_processing_certificate: data.payment_processing_certificate,+ },+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize Apple Pay certificate cache payload")?;++ let private_key_payload: ApplePayCertificateKeyWrapperData =+ serde_json::from_str(private_key.peek())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse stored Apple Pay private key payload")?;++ let key_wrapper = serde_json::to_value(ApplePayCertificateKeyWrapper {+ data: private_key_payload,+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize Apple Pay certificate cache key wrapper")?;+ let key_wrapper: Secret<serde_json::Value> = Secret::new(key_wrapper);++ let identifier =+ km_types::Identifier::Merchant(account_key_store.merchant_id.clone());++ let encrypted_cache = domain::types::crypto_operation(+ key_manager_state,+ common_utils::type_name!(domain::HierarchicalResource),+ domain::types::CryptoOperation::Encrypt(key_wrapper),+ identifier,+ account_key_store.key.peek(),+ )+ .await+ .and_then(|value| value.try_into_operation())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encrypt decrypt-time certificate cache")?;++ let update = ApplePayCertificateResourceUpdate {+ apple_pay_certificates: Some(Secret::new(plain_data)),+ apple_pay_certificates_encrypted: Some(encrypted_cache.into()),+ };+ link_hierarchical_resource_data_to_scope(db, account_key_store, account, &update)+ .await+ }+ None => Ok(()),+ }+ }+}++impl ApplePayCertificateResource {+ async fn upload(+ state: &SessionState,+ resource: domain::HierarchicalResource,+ org_key: &Secret<Vec<u8>>,+ req: api_resources::UploadCertificateRequest,+ ) -> RouterResult<api_resources::UploadCertificateResponse> {+ let db = state.store.as_ref();++ let private_key_payload = resource+ .encrypted_data+ .as_ref()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Resource has no private key — cannot verify uploaded certificate")?+ .peek()+ .clone();+ let private_key_pem: ApplePayCertificateKeyWrapperData =+ serde_json::from_str(&private_key_payload)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse stored Apple Pay private key payload")?;++ let certificate = parse_certificate_from_base64_der(&req.certificate)?;++ let keys_match = certificate_matches_private_key(+ &certificate,+ private_key_pem.payment_processing_certificate_key.peek(),+ )+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "Failed to verify uploaded certificate".to_string(),+ })?;+ if !keys_match {+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message: "Uploaded certificate does not match the generated key".to_string(),+ }));+ }++ let apple_merchant_identifier = parse_apple_merchant_identifier(&certificate)+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "Could not parse Apple merchant identifier from certificate".to_string(),+ })?;++ let data = ApplePayCertificateData {+ status: ApplePayCertificateStatus::Active,+ apple_pay_merchant_identifier: Some(apple_merchant_identifier),+ payment_processing_certificate: Some(req.certificate),+ };++ let updated = db+ .update_linked_resource_data(+ resource.id.clone(),+ domain::HierarchicalResourceDataUpdate {+ data: Secret::new(+ serde_json::to_value(&data)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to serialize Apple Pay certificate resource data",+ )?,+ ),+ },+ org_key,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to persist uploaded Apple Pay certificate")?;++ Ok(api_resources::UploadCertificateResponse {+ id: updated.id,+ created_at: updated.created_at,+ })+ }+}++trait RequestorHierarchicalResourceUpdate {+ fn for_merchant_connector_account(&self) -> domain::MerchantConnectorAccountUpdate;+ fn for_profile(&self) -> domain::ProfileUpdate;+ fn for_merchant_account(&self) -> domain::MerchantAccountUpdate;+}++struct ApplePayCertificateResourceUpdate {+ apple_pay_certificates: Option<Secret<serde_json::Value>>,+ apple_pay_certificates_encrypted: Option<common_utils::encryption::Encryption>,+}++impl ApplePayCertificateResourceUpdate {+ fn apple_pay_certificates(&self) -> Option<serde_json::Value> {+ self.apple_pay_certificates+ .as_ref()+ .map(|data| data.peek().clone())+ }+}++impl RequestorHierarchicalResourceUpdate for ApplePayCertificateResourceUpdate {+ fn for_merchant_connector_account(&self) -> domain::MerchantConnectorAccountUpdate {+ domain::MerchantConnectorAccountUpdate::ApplePayCertificateCacheUpdate {+ apple_pay_certificates: self.apple_pay_certificates(),+ apple_pay_certificates_encrypted: self.apple_pay_certificates_encrypted.clone(),+ }+ }++ fn for_profile(&self) -> domain::ProfileUpdate {+ domain::ProfileUpdate::ApplePayCertificateCacheUpdate {+ apple_pay_certificates: self.apple_pay_certificates(),+ apple_pay_certificates_encrypted: self.apple_pay_certificates_encrypted.clone(),+ }+ }++ fn for_merchant_account(&self) -> domain::MerchantAccountUpdate {+ domain::MerchantAccountUpdate::ApplePayCertificateCacheUpdate {+ apple_pay_certificates: self.apple_pay_certificates(),+ apple_pay_certificates_encrypted: self.apple_pay_certificates_encrypted.clone(),+ }+ }+}++enum RequestorAccount {+ MerchantConnectorAccount(Box<domain::MerchantConnectorAccount>),+ Profile(Box<domain::Profile>),+ MerchantAccount(Box<domain::MerchantAccount>),+}++fn parse_requestor_id<T>(value: &str) -> RouterResult<T>+where+ T: TryFrom<+ std::borrow::Cow<'static, str>,+ Error = error_stack::Report<common_utils::errors::ValidationError>,+ >,+{+ T::try_from(std::borrow::Cow::Owned(value.to_owned())).change_context(+ errors::ApiErrorResponse::InvalidRequestData {+ message: "invalid requestor_id".to_string(),+ },+ )+}++/// Fetches the target MCA/profile/merchant_account scoped strictly to `processor`'s own+/// merchant — a `NotFound` here is itself the authorization check, no separate org-membership+/// check is needed since the fetch can never return an entity belonging to a different merchant.+#[cfg(feature = "v1")]+async fn fetch_requestor_account(+ db: &dyn StorageInterface,+ processor: &domain::Processor,+ requestor_type: common_enums::ResourceRequestorType,+ requestor_id: &str,+) -> RouterResult<RequestorAccount> {+ match requestor_type {+ common_enums::ResourceRequestorType::MerchantConnectorAccount => {+ let mca_id = parse_requestor_id::<id_type::MerchantConnectorAccountId>(requestor_id)?;+ let mca = db+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ processor.get_account().get_id(),+ &mca_id,+ processor.get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: mca_id.get_string_repr().to_string(),+ },+ )?;+ Ok(RequestorAccount::MerchantConnectorAccount(Box::new(mca)))+ }+ common_enums::ResourceRequestorType::Profile => {+ let profile_id = parse_requestor_id::<id_type::ProfileId>(requestor_id)?;+ let profile = db+ .find_business_profile_by_merchant_id_profile_id(+ processor.get_key_store(),+ processor.get_account().get_id(),+ &profile_id,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;+ Ok(RequestorAccount::Profile(Box::new(profile)))+ }+ common_enums::ResourceRequestorType::MerchantAccount => {+ let merchant_id = parse_requestor_id::<id_type::MerchantId>(requestor_id)?;+ if &merchant_id != processor.get_account().get_id() {+ return Err(report!(errors::ApiErrorResponse::MerchantAccountNotFound));+ }+ Ok(RequestorAccount::MerchantAccount(Box::new(+ processor.get_account().clone(),+ )))+ }+ }+}++#[cfg(feature = "v2")]+async fn fetch_requestor_account(+ _db: &dyn StorageInterface,+ _processor: &domain::Processor,+ _requestor_type: common_enums::ResourceRequestorType,+ _requestor_id: &str,+) -> RouterResult<RequestorAccount> {+ Err(report!(errors::ApiErrorResponse::NotSupported {+ message: "Resource linking is not supported for v2".to_string(),+ }))+}++/// Reads the linked-certificate cache off an already-fetched `RequestorAccount`, cascading to+/// its profile and then its merchant account exactly like `resolve_apple_pay_certificate_cache`+/// used to — safely, since an MCA's own profile/merchant are inherent properties of an entity+/// already scoped to `processor`'s merchant, not caller-supplied ids.+#[cfg(feature = "v1")]+async fn resolve_apple_pay_certificate_data(+ db: &dyn StorageInterface,+ processor: &domain::Processor,+ account: &RequestorAccount,+) -> Option<serde_json::Value> {+ match account {+ RequestorAccount::MerchantConnectorAccount(mca) => match mca.apple_pay_certificates.clone()+ {+ Some(data) => Some(data),+ None => {+ let profile = db+ .find_business_profile_by_merchant_id_profile_id(+ processor.get_key_store(),+ processor.get_account().get_id(),+ &mca.profile_id,+ )+ .await+ .ok()?;+ profile+ .apple_pay_certificates+ .or_else(|| processor.get_account().apple_pay_certificates.clone())+ }+ },+ RequestorAccount::Profile(profile) => profile+ .apple_pay_certificates+ .clone()+ .or_else(|| processor.get_account().apple_pay_certificates.clone()),+ RequestorAccount::MerchantAccount(merchant_account) => {+ merchant_account.apple_pay_certificates.clone()+ }+ }+}++#[cfg(feature = "v2")]+async fn resolve_apple_pay_certificate_data(+ _db: &dyn StorageInterface,+ _processor: &domain::Processor,+ _account: &RequestorAccount,+) -> Option<serde_json::Value> {+ None+}++async fn link_hierarchical_resource_data_to_scope(+ db: &dyn StorageInterface,+ key_store: &domain::MerchantKeyStore,+ account: RequestorAccount,+ update: &impl RequestorHierarchicalResourceUpdate,+) -> RouterResult<()> {+ match account {+ RequestorAccount::MerchantConnectorAccount(mca) => {+ db.update_merchant_connector_account(+ *mca,+ update.for_merchant_connector_account().into(),+ key_store,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to link resource data to merchant connector account")?;+ }+ RequestorAccount::Profile(profile) => {+ db.update_profile_by_profile_id(key_store, *profile, update.for_profile())+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to link resource data to profile")?;+ }+ RequestorAccount::MerchantAccount(merchant_account) => {+ db.update_merchant(*merchant_account, update.for_merchant_account(), key_store)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to link resource data to merchant account")?;+ }+ }++ Ok(())+}++pub async fn generate_hierarchical_resource(+ state: SessionState,+ processor: domain::Processor,+ req: api_resources::GenerateHierarchicalResourceRequest,+) -> RouterResponse<api_resources::GenerateHierarchicalResourceResponse> {+ let db = state.store.as_ref();+ let key_manager_state: &KeyManagerState = &(&state).into();+ let organization_id = processor.get_account().organization_id.clone();++ let org_key_store =+ ensure_organization_key_store(db, key_manager_state, &organization_id).await?;++ let (resource, response) = match req.resource_type {+ common_enums::ResourceType::ApplePayCertificate => {+ ApplePayCertificateResource::generate(&state, &processor, &org_key_store).await?+ }+ };++ db.insert_linked_resource(resource, &org_key_store.key)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to persist generated resource")?;++ Ok(ApplicationResponse::Json(response))+}++fn generate_ec_keypair_and_csr(+) -> error_stack::Result<(Secret<String>, String), openssl::error::ErrorStack> {+ let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)?;+ let ec_key = EcKey::generate(&group)?;+ let pkey = PKey::from_ec_key(ec_key)?;++ let mut name_builder = X509NameBuilder::new()?;+ name_builder.append_entry_by_text("CN", "Apple Pay Payment Processing Certificate Request")?;+ let name = name_builder.build();++ let mut req_builder = X509Req::builder()?;+ req_builder.set_subject_name(&name)?;+ req_builder.set_pubkey(&pkey)?;+ req_builder.sign(&pkey, openssl::hash::MessageDigest::sha256())?;+ let csr = req_builder.build();++ let csr_pem = csr.to_pem()?;+ let private_key_pem = pkey.private_key_to_pem_pkcs8()?;++ Ok((+ Secret::new(String::from_utf8_lossy(&private_key_pem).to_string()),+ String::from_utf8_lossy(&csr_pem).to_string(),+ ))+}++pub async fn upload_hierarchical_resource(+ state: SessionState,+ processor: domain::Processor,+ resource_id: id_type::ResourceId,+ req: api_resources::UploadCertificateRequest,+) -> RouterResponse<api_resources::UploadCertificateResponse> {+ let db = state.store.as_ref();+ let key_manager_state: &KeyManagerState = &(&state).into();+ let organization_id = processor.get_account().organization_id.clone();++ let scope_id = db+ .find_resource_scope_id(resource_id.clone())+ .await+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {+ message: "resource not found".to_string(),+ })?;+ authorize_scope_id_belongs_to_org(&scope_id, &organization_id)?;++ let org_key_store =+ ensure_organization_key_store(db, key_manager_state, &organization_id).await?;++ let resource = db+ .find_linked_resource_by_id(resource_id.clone(), &org_key_store.key)+ .await+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {+ message: "resource not found".to_string(),+ })?;++ let resource_type = parse_resource_type(&resource)?;++ let response = match resource_type {+ common_enums::ResourceType::ApplePayCertificate => {+ ApplePayCertificateResource::upload(&state, resource, &org_key_store.key, req).await?+ }+ };++ Ok(ApplicationResponse::Json(response))+}++fn parse_resource_type(+ resource: &domain::HierarchicalResource,+) -> RouterResult<common_enums::ResourceType> {+ resource+ .resource_type+ .parse::<common_enums::ResourceType>()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!(+ "Unrecognized resource_type '{}' stored for resource {:?}",+ resource.resource_type, resource.id+ )+ })+}++fn parse_certificate_from_base64_der(certificate_base64: &str) -> RouterResult<X509> {+ let der_bytes = crate::consts::BASE64_ENGINE+ .decode(certificate_base64)+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "certificate is not valid base64".to_string(),+ })?;++ X509::from_der(&der_bytes).change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "certificate is not a valid DER-encoded X.509 certificate".to_string(),+ })+}++fn certificate_matches_private_key(+ certificate: &X509,+ private_key_pem: &str,+) -> error_stack::Result<bool, openssl::error::ErrorStack> {+ let certificate_public_key_der = certificate.public_key()?.public_key_to_der()?;++ let private_key = PKey::private_key_from_pem(private_key_pem.as_bytes())?;+ let private_key_public_der = private_key.public_key_to_der()?;++ Ok(certificate_public_key_der == private_key_public_der)+}++fn parse_apple_merchant_identifier(+ certificate: &X509,+) -> error_stack::Result<String, openssl::error::ErrorStack> {+ let common_name = certificate+ .subject_name()+ .entries_by_nid(Nid::COMMONNAME)+ .next()+ .ok_or_else(openssl::error::ErrorStack::get)?+ .data()+ .as_utf8()?+ .to_string();++ Ok(common_name+ .rsplit(':')+ .next()+ .unwrap_or(&common_name)+ .trim()+ .to_string())+}++pub async fn list_hierarchical_resources(+ state: SessionState,+ processor: domain::Processor,+ req: api_resources::ListHierarchicalResourcesRequest,+) -> RouterResponse<api_resources::ListHierarchicalResourcesResponse> {+ let db = state.store.as_ref();+ let key_manager_state: &KeyManagerState = &(&state).into();+ let organization_id = processor.get_account().organization_id.clone();++ let org_key_store =+ ensure_organization_key_store(db, key_manager_state, &organization_id).await?;++ let resources = db+ .list_linked_resources_by_scope_id_and_resource_type(+ organization_id.get_string_repr().to_string(),+ req.resource_type.to_string(),+ &org_key_store.key,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to list resources")?;++ let effective_resource_id = match (req.scope_type, req.scope_id) {+ (Some(scope_type), Some(scope_id)) => {+ let account = fetch_requestor_account(db, &processor, scope_type, &scope_id).await?;+ match resolve_apple_pay_certificate_data(db, &processor, &account).await {+ Some(data) => data+ .get("resource_id")+ .and_then(|value| value.as_str())+ .map(parse_requestor_id::<id_type::ResourceId>)+ .transpose()?,+ None => None,+ }+ }+ _ => None,+ };++ let resources = resources+ .iter()+ .filter(|resource| hierarchical_resource_is_linkable(resource).unwrap_or(false))+ .map(|resource| hierarchical_resource_summary(resource, effective_resource_id.as_ref()))+ .collect::<RouterResult<Vec<_>>>()?;++ Ok(ApplicationResponse::Json(+ api_resources::ListHierarchicalResourcesResponse { resources },+ ))+}++fn hierarchical_resource_is_linkable(+ resource: &domain::HierarchicalResource,+) -> RouterResult<bool> {+ let resource_type = parse_resource_type(resource)?;++ match resource_type {+ common_enums::ResourceType::ApplePayCertificate => {+ ApplePayCertificateResource::is_linkable(resource)+ }+ }+}++fn hierarchical_resource_summary(+ resource: &domain::HierarchicalResource,+ effective_resource_id: Option<&id_type::ResourceId>,+) -> RouterResult<api_resources::HierarchicalResourceSummary> {+ let resource_type = parse_resource_type(resource)?;++ let (display_schema, display_data) = match resource_type {+ common_enums::ResourceType::ApplePayCertificate => (+ ApplePayCertificateResource::display_schema(),+ ApplePayCertificateResource::display_data(resource)?,+ ),+ };++ Ok(api_resources::HierarchicalResourceSummary {+ id: resource.id.clone(),+ display_schema,+ display_data,+ created_at: resource.created_at,+ is_linked: effective_resource_id == Some(&resource.id),+ })+}++pub async fn link_hierarchical_resource(+ state: SessionState,+ processor: domain::Processor,+ resource_id: id_type::ResourceId,+ req: api_resources::LinkHierarchicalResourceRequest,+) -> RouterResponse<api_resources::LinkHierarchicalResourceResponse> {+ let db = state.store.as_ref();+ let key_manager_state: &KeyManagerState = &(&state).into();+ let merchant_account = processor.get_account();+ let organization_id = merchant_account.organization_id.clone();++ let scope_id = db+ .find_resource_scope_id(resource_id.clone())+ .await+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {+ message: "resource not found".to_string(),+ })?;+ authorize_scope_id_belongs_to_org(&scope_id, &organization_id)?;++ let account =+ fetch_requestor_account(db, &processor, req.requestor_type, &req.requestor_id).await?;++ let org_key_store =+ ensure_organization_key_store(db, key_manager_state, &organization_id).await?;++ let resource = db+ .find_linked_resource_by_id(resource_id.clone(), &org_key_store.key)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch resource to link")?;++ let resource_type = parse_resource_type(&resource)?;++ match resource_type {+ common_enums::ResourceType::ApplePayCertificate => {+ ApplePayCertificateResource::on_link(+ &state,+ key_manager_state,+ &resource,+ &resource_id,+ account,+ processor.get_key_store(),+ )+ .await?;+ }+ }++ Ok(ApplicationResponse::Json(+ api_resources::LinkHierarchicalResourceResponse { id: resource_id },+ ))+}++fn authorize_scope_id_belongs_to_org(+ scope_id: &str,+ organization_id: &id_type::OrganizationId,+) -> RouterResult<()> {+ if scope_id != organization_id.get_string_repr() {+ return Err(report!(errors::ApiErrorResponse::AccessForbidden {+ resource: "resource".to_string(),+ }));+ }+ Ok(())+}++pub(crate) async fn ensure_organization_key_store(+ db: &dyn StorageInterface,+ key_manager_state: &KeyManagerState,+ organization_id: &id_type::OrganizationId,+) -> RouterResult<domain::MerchantKeyStore> {+ let org_key_identifier = organization_id+ .as_merchant_key_identifier()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to derive organization key identifier")?;++ let master_key = db.get_master_key();++ match db+ .get_merchant_key_store_by_merchant_id(&org_key_identifier, &master_key.to_vec().into())+ .await+ {+ Ok(key_store) => Ok(key_store),+ Err(error) if error.current_context().is_db_not_found() => {+ create_organization_key_store(db, key_manager_state, &org_key_identifier, master_key)+ .await+ }+ Err(error) => Err(error).change_context(errors::ApiErrorResponse::InternalServerError),+ }+}++async fn create_organization_key_store(+ db: &dyn StorageInterface,+ key_manager_state: &KeyManagerState,+ org_key_identifier: &id_type::MerchantId,+ master_key: &[u8],+) -> RouterResult<domain::MerchantKeyStore> {+ let key = crate::services::generate_aes256_key()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to generate aes 256 key for organization")?;++ let identifier = km_types::Identifier::Merchant(org_key_identifier.clone());++ common_utils::keymanager::transfer_key_to_key_manager(+ key_manager_state,+ EncryptionTransferRequest {+ identifier: identifier.clone(),+ key: hyperswitch_masking::StrongSecret::new(crate::consts::BASE64_ENGINE.encode(key)),+ },+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to insert organization key to KeyManager")?;++ let key_store = domain::MerchantKeyStore {+ merchant_id: org_key_identifier.clone(),+ key: domain::types::crypto_operation(+ key_manager_state,+ common_utils::type_name!(domain::MerchantKeyStore),+ domain::types::CryptoOperation::EncryptLocally(key.to_vec().into()),+ identifier,+ master_key,+ )+ .await+ .and_then(|value| value.try_into_operation())+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to encrypt organization key")?,+ created_at: date_time::now(),+ };++ db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into())+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to insert organization key store")?;++ Ok(key_store)+}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 4f7677c7e5..383a2d132e 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -829,6 +829,7 @@ where&operation,state,platform,+ &business_profile,&mut payment_data,connector.as_ref(),)@@ -1149,6 +1150,7 @@ wherecomplete_postprocessing_steps_if_required(state,platform.get_processor(),+ &business_profile,&mca,&connector.connector_data,&mut payment_data,@@ -1375,6 +1377,7 @@ wherecomplete_postprocessing_steps_if_required(state,platform.get_processor(),+ &business_profile,&mca,&connector_data,&mut payment_data,@@ -1804,6 +1807,7 @@ wherecomplete_postprocessing_steps_if_required(state,platform.get_processor(),+ &business_profile,&mca,&connector,&mut payment_data,@@ -3318,6 +3322,7 @@ wherecomplete_postprocessing_steps_if_required(state,platform.get_processor(),+ &business_profile,&merchant_connector_account,&connector,&mut payment_data,@@ -3458,6 +3463,7 @@ wherestate,connector.connector.id(),platform.get_processor(),+ business_profile,&merchant_connector_account,None,Some(header_payload),@@ -5641,6 +5647,7 @@ pub async fn get_decrypted_wallet_pm_token_and_set_pm_data<F, Req, D>(operation: &BoxedOperation<'_, F, Req, D>,state: &SessionState,platform: &domain::Platform,+ business_profile: &domain::Profile,payment_data: &mut D,connector_call_type_optional: Option<&ConnectorCallType>,) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse>@@ -5696,7 +5703,14 @@ where}let decide_wallet_flow = wallet- .decide_wallet_flow(state, payment_data, &merchant_connector_account)+ .decide_wallet_flow(+ state,+ payment_data,+ &merchant_connector_account,+ business_profile,+ platform.get_processor(),+ )+ .await.attach_printable("Failed to decide wallet flow")?;let payment_method_token = match decide_wallet_flow {@@ -5778,6 +5792,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>(state: &SessionState,processor: &domain::Processor,initiator: Option<&domain::Initiator>,+ business_profile: &domain::Profile,connector: api::ConnectorData,operation: &BoxedOperation<'_, F, ApiRequest, D>,payment_data: &mut D,@@ -5873,6 +5888,7 @@ whereconnector_customer_map,processor,initiator,+ business_profile,&merchant_connector_account,payment_data,router_data.access_token.as_ref(),@@ -6272,6 +6288,7 @@ wherestate,connector.connector.id(),platform.get_processor(),+ business_profile,&merchant_connector_account,merchant_recipient_data,None,@@ -6373,6 +6390,7 @@ where&updated_state,processor,initiator,+ business_profile,connector,operation,payment_data,@@ -7239,6 +7257,7 @@ wherestate,connector.connector.id(),platform.get_processor(),+ business_profile,&merchant_connector_account,merchant_recipient_data,Some(header_payload.clone()),@@ -7539,11 +7558,13 @@ whereOk(None)}- fn decide_wallet_flow(+ async fn decide_wallet_flow(&self,state: &SessionState,payment_data: &D,merchant_connector_account: &helpers::MerchantConnectorAccountType,+ business_profile: &domain::Profile,+ processor: &domain::Processor,) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse>;async fn decrypt_wallet_token(@@ -7559,11 +7580,13 @@ whereF: Send + Clone,D: OperationSessionGetters<F> + Send + Sync + Clone,{- fn decide_wallet_flow(+ async fn decide_wallet_flow(&self,state: &SessionState,_payment_data: &D,_merchant_connector_account: &helpers::MerchantConnectorAccountType,+ _business_profile: &domain::Profile,+ _processor: &domain::Processor,) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {let paze_keys = state.conf@@ -7667,13 +7690,21 @@ where}}- fn decide_wallet_flow(+ async fn decide_wallet_flow(&self,state: &SessionState,payment_data: &D,merchant_connector_account: &helpers::MerchantConnectorAccountType,+ business_profile: &domain::Profile,+ processor: &domain::Processor,) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {- let apple_pay_metadata = check_apple_pay_metadata(state, Some(merchant_connector_account));+ let apple_pay_metadata = check_apple_pay_metadata(+ state,+ Some(merchant_connector_account),+ business_profile,+ processor,+ )+ .await;add_apple_pay_flow_metrics(&apple_pay_metadata,@@ -7766,11 +7797,13 @@ whereOk(None)}}- fn decide_wallet_flow(+ async fn decide_wallet_flow(&self,state: &SessionState,_payment_data: &D,merchant_connector_account: &helpers::MerchantConnectorAccountType,+ _business_profile: &domain::Profile,+ _processor: &domain::Processor,) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {Ok(get_google_pay_connector_wallet_details(state, merchant_connector_account)@@ -8231,6 +8264,7 @@ wherestate,connector_id,processor,+ business_profile,&merchant_connector_account,None,Some(header_payload.clone()),@@ -8553,6 +8587,7 @@ pub async fn call_create_connector_customer_if_required<F, Req, D>(connector_customer_map: Option<&pii::SecretSerdeValue>,processor: &domain::Processor,initiator: Option<&domain::Initiator>,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,payment_data: &mut D,access_token: Option<&AccessToken>,@@ -8625,6 +8660,7 @@ wherestate,connector.connector.id(),processor,+ business_profile,merchant_connector_account,None,None,@@ -8847,6 +8883,7 @@ whereasync fn complete_postprocessing_steps_if_required<F, Q, RouterDReq, D>(state: &SessionState,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_conn_account: &helpers::MerchantConnectorAccountType,connector: &api::ConnectorData,payment_data: &mut D,@@ -8868,6 +8905,7 @@ wherestate,connector.connector.id(),processor,+ business_profile,merchant_conn_account,None,header_payload,@@ -9196,34 +9234,119 @@ async fn get_feature_data(}}-fn decide_apple_pay_flow(+async fn decide_apple_pay_flow(state: &SessionState,payment_method_type: Option<enums::PaymentMethodType>,merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>,+ business_profile: &domain::Profile,+ processor: &domain::Processor,) -> Option<domain::ApplePayFlow> {- payment_method_type.and_then(|pmt| match pmt {- enums::PaymentMethodType::ApplePay => {- check_apple_pay_metadata(state, merchant_connector_account)+ match payment_method_type {+ Some(enums::PaymentMethodType::ApplePay) => {+ check_apple_pay_metadata(+ state,+ merchant_connector_account,+ business_profile,+ processor,+ )+ .await}_ => None,+ }+}++#[cfg(feature = "v1")]+struct ApplePayCertificateAccounts<'a> {+ processor: &'a domain::Processor,+ business_profile: Option<&'a domain::Profile>,+ merchant_connector_account: &'a helpers::MerchantConnectorAccountType,+}++#[cfg(feature = "v1")]+async fn resolve_managed_apple_pay_certificate(+ accounts: &ApplePayCertificateAccounts<'_>,+) -> Option<payments_api::PaymentProcessingDetails> {+ let (data, encrypted_data) = accounts+ .merchant_connector_account+ .get_apple_pay_certificate_cache()+ .or_else(|| {+ accounts.business_profile.and_then(|profile| {+ profile+ .apple_pay_certificates+ .clone()+ .map(|data| (data, profile.apple_pay_certificates_encrypted.clone()))+ })+ })+ .or_else(|| {+ accounts+ .processor+ .get_account()+ .apple_pay_certificates+ .clone()+ .map(|data| {+ (+ data,+ accounts+ .processor+ .get_account()+ .apple_pay_certificates_encrypted+ .clone(),+ )+ })+ })?;++ let certificate = data+ .get("data")+ .and_then(|data| data.get("payment_processing_certificate"))+ .and_then(|value| value.as_str())?+ .to_string();+ let certificate_key_json: Secret<serde_json::Value> = encrypted_data?.into_inner();+ let certificate_key = certificate_key_json+ .peek()+ .get("data")+ .and_then(|data| data.get("payment_processing_certificate_key"))+ .and_then(|value| value.as_str())?+ .to_string();++ Some(payments_api::PaymentProcessingDetails {+ payment_processing_certificate: Secret::new(certificate),+ payment_processing_certificate_key: Secret::new(certificate_key),})}-fn check_apple_pay_metadata(+async fn check_apple_pay_metadata(state: &SessionState,merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>,+ _business_profile: &domain::Profile,+ _processor: &domain::Processor,) -> Option<domain::ApplePayFlow> {- merchant_connector_account.and_then(|mca| {- let metadata = mca.get_metadata();- metadata.and_then(|apple_pay_metadata| {- let parsed_metadata = get_applepay_metadata(Some(apple_pay_metadata.clone()));-- parsed_metadata.ok().and_then(|metadata| match metadata {- api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(- apple_pay_combined,- ) => match apple_pay_combined.get_combined_metadata_required() {- Ok(api_models::payments::ApplePayCombinedMetadata::Simplified { .. }) => {- Some(domain::ApplePayFlow::DecryptAtApplication(+ let mca = merchant_connector_account?;++ #[cfg(feature = "v1")]+ let managed_certificate = resolve_managed_apple_pay_certificate(&ApplePayCertificateAccounts {+ processor: _processor,+ business_profile: Some(_business_profile),+ merchant_connector_account: mca,+ })+ .await+ .map(domain::ApplePayFlow::DecryptAtApplication);+ #[cfg(not(feature = "v1"))]+ let managed_certificate: Option<domain::ApplePayFlow> = None;++ match managed_certificate {+ Some(managed_certificate) => Some(managed_certificate),+ None => {+ let metadata = mca.get_metadata();+ metadata.and_then(|apple_pay_metadata| {+ let parsed_metadata = get_applepay_metadata(Some(apple_pay_metadata.clone()));++ parsed_metadata.ok().and_then(|metadata| match metadata {+ api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(+ apple_pay_combined,+ ) => match apple_pay_combined.get_combined_metadata_required() {+ Ok(api_models::payments::ApplePayCombinedMetadata::Simplified {+ ..+ }) => Some(domain::ApplePayFlow::DecryptAtApplication(payments_api::PaymentProcessingDetails {payment_processing_certificate: state.conf@@ -9238,44 +9361,44 @@ fn check_apple_pay_metadata(.apple_pay_ppc_key.clone(),},- ))- }- Ok(api_models::payments::ApplePayCombinedMetadata::Manual {- payment_request_data: _,- session_token_data,- }) => {- if let Some(manual_payment_processing_details_at) =- session_token_data.payment_processing_details_at- {- match manual_payment_processing_details_at {- payments_api::PaymentProcessingDetailsAt::Hyperswitch(- payment_processing_details,- ) => Some(domain::ApplePayFlow::DecryptAtApplication(- payment_processing_details,- )),- payments_api::PaymentProcessingDetailsAt::Connector => {- Some(domain::ApplePayFlow::SkipDecryption)+ )),+ Ok(api_models::payments::ApplePayCombinedMetadata::Manual {+ payment_request_data: _,+ session_token_data,+ }) => {+ if let Some(manual_payment_processing_details_at) =+ session_token_data.payment_processing_details_at+ {+ match manual_payment_processing_details_at {+ payments_api::PaymentProcessingDetailsAt::Hyperswitch(+ payment_processing_details,+ ) => Some(domain::ApplePayFlow::DecryptAtApplication(+ payment_processing_details,+ )),+ payments_api::PaymentProcessingDetailsAt::Connector => {+ Some(domain::ApplePayFlow::SkipDecryption)+ }}+ } else {+ Some(domain::ApplePayFlow::SkipDecryption)}- } else {- Some(domain::ApplePayFlow::SkipDecryption)}- }- Err(_) => {- // In the case were only predecrypted token in enabled donot throw error , just skip decryption- if apple_pay_combined.is_predecrypted_token_supported() {- Some(domain::ApplePayFlow::SkipDecryption)- } else {- None+ Err(_) => {+ // In the case were only predecrypted token in enabled donot throw error , just skip decryption+ if apple_pay_combined.is_predecrypted_token_supported() {+ Some(domain::ApplePayFlow::SkipDecryption)+ } else {+ None+ }}+ },+ api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => {+ Some(domain::ApplePayFlow::SkipDecryption)}- },- api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => {- Some(domain::ApplePayFlow::SkipDecryption)- }+ })})- })- })+ }+ }}fn get_google_pay_connector_wallet_details(@@ -9929,6 +10052,7 @@ whereasync fn decrypt_apple_pay_wallet_for_eligibility(state: &SessionState,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_id: &id_type::MerchantConnectorAccountId,apple_pay_wallet_data: &domain::ApplePayWalletData,) -> RouterResult<Option<domain::EligibilityPaymentMethodData>> {@@ -9950,23 +10074,32 @@ async fn decrypt_apple_pay_wallet_for_eligibility(.ok().map(|merchant_connector_account| {helpers::MerchantConnectorAccountType::DbVal(Box::new(merchant_connector_account))- })- .and_then(|merchant_connector_account| {- check_apple_pay_metadata(state, Some(&merchant_connector_account))- .and_then(|apple_pay_flow| match apple_pay_flow {- domain::ApplePayFlow::DecryptAtApplication(payment_processing_details) => {- Some(payment_processing_details)- }- domain::ApplePayFlow::SkipDecryption => None,- })- .or_else(|| {+ });++ let payment_processing_details = match payment_processing_details {+ Some(merchant_connector_account) => {+ match check_apple_pay_metadata(+ state,+ Some(&merchant_connector_account),+ business_profile,+ processor,+ )+ .await+ {+ Some(domain::ApplePayFlow::DecryptAtApplication(payment_processing_details)) => {+ Some(payment_processing_details)+ }+ Some(domain::ApplePayFlow::SkipDecryption) | None => {logger::warn!(merchant_connector_id = merchant_connector_id.get_string_repr(),"Apple Pay decrypt-at-application not configured for this connector account; skipping eligibility decryption");None- })- });+ }+ }+ }+ None => None,+ };match payment_processing_details {Some(payment_processing_details) => {@@ -14247,6 +14380,7 @@ impl EligibilityCheck for BlockListCheck {decrypt_apple_pay_wallet_for_eligibility(state,platform.get_processor(),+ business_profile,merchant_connector_id,apple_pay_data,)diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rsindex e023e2db80..b3fc4813c7 100644--- a/crates/router/src/core/payments/flows.rs+++ b/crates/router/src/core/payments/flows.rs@@ -51,6 +51,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> {state: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<domain_payments::HeaderPayload>,diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rsindex cb83fe2970..4234b52dd5 100644--- a/crates/router/src/core/payments/flows/approve_flow.rs+++ b/crates/router/src/core/payments/flows/approve_flow.rs@@ -38,6 +38,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -52,6 +53,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex f801104967..6ecbc2c81b 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -145,6 +145,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<domain_payments::HeaderPayload>,@@ -169,6 +170,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rsindex e6d82ff650..99099e9768 100644--- a/crates/router/src/core/payments/flows/cancel_flow.rs+++ b/crates/router/src/core/payments/flows/cancel_flow.rs@@ -21,6 +21,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paymstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -35,6 +36,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paymself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rsindex 944badffab..a964991279 100644--- a/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs+++ b/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs@@ -39,6 +39,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -53,6 +54,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/cancel_post_capture_sync_flow.rs b/crates/router/src/core/payments/flows/cancel_post_capture_sync_flow.rsindex cac69cc2b2..6d5d43dec4 100644--- a/crates/router/src/core/payments/flows/cancel_post_capture_sync_flow.rs+++ b/crates/router/src/core/payments/flows/cancel_post_capture_sync_flow.rs@@ -40,6 +40,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -54,6 +55,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rsindex d1ce1f7261..888759b509 100644--- a/crates/router/src/core/payments/flows/capture_flow.rs+++ b/crates/router/src/core/payments/flows/capture_flow.rs@@ -23,6 +23,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -37,6 +38,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 4531a7724a..8190a50b7e 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -50,6 +50,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -70,6 +71,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/extend_authorization_flow.rs b/crates/router/src/core/payments/flows/extend_authorization_flow.rsindex 5356655c63..60a8fd3d3c 100644--- a/crates/router/src/core/payments/flows/extend_authorization_flow.rs+++ b/crates/router/src/core/payments/flows/extend_authorization_flow.rs@@ -39,6 +39,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -53,6 +54,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rsindex 5ae13a9bcb..228093b1e1 100644--- a/crates/router/src/core/payments/flows/external_proxy_flow.rs+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs@@ -44,6 +44,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ _business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<domain_payments::HeaderPayload>,diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rsindex d49ccf1412..f0950ebeb7 100644--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs@@ -26,6 +26,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -40,6 +41,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs b/crates/router/src/core/payments/flows/post_session_tokens_flow.rsindex 81f4b075e1..7609e885e6 100644--- a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs+++ b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs@@ -25,6 +25,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -39,6 +40,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/pre_authorize_void_flow.rs b/crates/router/src/core/payments/flows/pre_authorize_void_flow.rsindex 7c0a16107a..eabfa831f6 100644--- a/crates/router/src/core/payments/flows/pre_authorize_void_flow.rs+++ b/crates/router/src/core/payments/flows/pre_authorize_void_flow.rs@@ -26,6 +26,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -40,6 +41,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rsindex ad78ca9a8c..ad5da95013 100644--- a/crates/router/src/core/payments/flows/psync_flow.rs+++ b/crates/router/src/core/payments/flows/psync_flow.rs@@ -27,6 +27,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Paymestate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<domain_payments::HeaderPayload>,@@ -43,6 +44,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Paymeself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rsindex 37a5eb92f2..04cf2fed4b 100644--- a/crates/router/src/core/payments/flows/reject_flow.rs+++ b/crates/router/src/core/payments/flows/reject_flow.rs@@ -21,6 +21,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pastate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -35,6 +36,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Paself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rsindex 9bc9319151..ef329b5447 100644--- a/crates/router/src/core/payments/flows/session_flow.rs+++ b/crates/router/src/core/payments/flows/session_flow.rs@@ -80,6 +80,7 @@ implstate: &routes::SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -98,6 +99,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/session_update_flow.rs b/crates/router/src/core/payments/flows/session_update_flow.rsindex ed7e4fa8de..73b55b80a7 100644--- a/crates/router/src/core/payments/flows/session_update_flow.rs+++ b/crates/router/src/core/payments/flows/session_update_flow.rs@@ -25,6 +25,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ _business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,_merchant_recipient_data: Option<types::MerchantRecipientData>,_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rsindex 9edfcf4136..2b38ed8415 100644--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs@@ -44,6 +44,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<domain_payments::HeaderPayload>,@@ -62,6 +63,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/update_metadata_flow.rs b/crates/router/src/core/payments/flows/update_metadata_flow.rsindex 98023f0d59..879df1dcc0 100644--- a/crates/router/src/core/payments/flows/update_metadata_flow.rs+++ b/crates/router/src/core/payments/flows/update_metadata_flow.rs@@ -25,6 +25,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -37,6 +38,7 @@ implself.clone(),connector_id,processor,+ business_profile,merchant_connector_account,merchant_recipient_data,header_payload,diff --git a/crates/router/src/core/payments/flows/update_post_confirm_flow.rs b/crates/router/src/core/payments/flows/update_post_confirm_flow.rsindex 8779a28f81..b37f46bb97 100644--- a/crates/router/src/core/payments/flows/update_post_confirm_flow.rs+++ b/crates/router/src/core/payments/flows/update_post_confirm_flow.rs@@ -26,6 +26,7 @@ implstate: &SessionState,connector_id: &str,processor: &domain::Processor,+ _business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,_merchant_recipient_data: Option<types::MerchantRecipientData>,_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 0043b548f3..5dd41a7e40 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -1958,6 +1958,7 @@ pub async fn construct_payment_router_data<'a, F, T>(payment_data: PaymentData<F>,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -2067,7 +2068,10 @@ wherestate,payment_data.payment_attempt.payment_method_type,Some(merchant_connector_account),- );+ business_profile,+ processor,+ )+ .await;let unified_address = if let Some(payment_method_info) =payment_data.payment_method_info.clone()@@ -2296,6 +2300,7 @@ pub async fn construct_payment_router_data_for_update_metadata<'a>(payment_data: PaymentData<api::UpdateMetadata>,connector_id: &str,processor: &domain::Processor,+ business_profile: &domain::Profile,merchant_connector_account: &helpers::MerchantConnectorAccountType,merchant_recipient_data: Option<types::MerchantRecipientData>,header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,@@ -2394,7 +2399,10 @@ pub async fn construct_payment_router_data_for_update_metadata<'a>(state,payment_data.payment_attempt.payment_method_type,Some(merchant_connector_account),- );+ business_profile,+ processor,+ )+ .await;let unified_address = if let Some(payment_method_info) =payment_data.payment_method_info.clone()diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex b4ce177e44..12d15df24b 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -361,7 +361,7 @@ pub async fn payouts_create_core(.with_provider_merchant_id(platform.get_provider().get_provider_merchant_id()).with_profile_id(profile_id.clone());// Create DB entries- let mut payout_data = payout_create_db_entries(+ let mut payout_data = Box::pin(payout_create_db_entries(&state,&platform,&req,@@ -372,7 +372,7 @@ pub async fn payouts_create_core(customer.as_ref(),payment_method.clone(),&dimensions,- )+ )).await?;let payout_attempt = payout_data.payout_attempt.to_owned();diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex 0a060d00ce..ebc81311ad 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -22,6 +22,7 @@ pub mod fraud_check;pub mod generic_link;pub mod gsm;pub mod health_check;+pub mod hierarchical_resource;pub mod kafka_store;pub mod locker_mock_up;pub mod mandate;@@ -132,6 +133,7 @@ pub trait StorageInterface:+ reverse_lookup::ReverseLookupInterface+ CardsInfoInterface<Error = StorageError>+ merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>+ + hierarchical_resource::HierarchicalResourceInterface<Error = StorageError>+ MasterKeyInterface+ payment_link::PaymentLinkInterface+ RedisConnInterface@@ -214,6 +216,7 @@ pub trait AccountsStorageInterface:+ business_profile::ProfileInterface<Error = StorageError>+ merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>+ merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>+ + hierarchical_resource::HierarchicalResourceInterface<Error = StorageError>+ dashboard_metadata::DashboardMetadataInterface+ RequestIdStore+ 'static@@ -231,6 +234,7 @@ pub trait AccountsStorageInterface:+ business_profile::ProfileInterface<Error = StorageError>+ merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>+ merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>+ + hierarchical_resource::HierarchicalResourceInterface<Error = StorageError>+ dashboard_metadata::DashboardMetadataInterface+ 'static{diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rsindex fb05f33741..830ecb0f22 100644--- a/crates/router/src/db/events.rs+++ b/crates/router/src/db/events.rs@@ -2001,6 +2001,8 @@ mod tests {network_tokenization_credentials: None,fingerprint_secret: None,offer_engine_config: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,});let merchant_account = state.storediff --git a/crates/router/src/db/hierarchical_resource.rs b/crates/router/src/db/hierarchical_resource.rsnew file mode 100644index 0000000000..b5ae12f8ab--- /dev/null+++ b/crates/router/src/db/hierarchical_resource.rs@@ -0,0 +1 @@+pub use hyperswitch_domain_models::hierarchical_resource::{self, HierarchicalResourceInterface};diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex ad9d45792e..d7e55ab2ea 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -81,6 +81,7 @@ use crate::{generic_link::GenericLinkInterface,gsm::GsmInterface,health_check::HealthCheckDbInterface,+ hierarchical_resource::HierarchicalResourceInterface,locker_mock_up::LockerMockUpInterface,mandate::MandateInterface,merchant_account::MerchantAccountInterface,@@ -3333,6 +3334,58 @@ impl MerchantKeyStoreInterface for KafkaStore {}}+#[async_trait::async_trait]+impl HierarchicalResourceInterface for KafkaStore {+ type Error = errors::StorageError;++ async fn insert_linked_resource(+ &self,+ resource: domain::HierarchicalResource,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, errors::StorageError> {+ self.diesel_store+ .insert_linked_resource(resource, key)+ .await+ }++ async fn find_linked_resource_by_id(+ &self,+ id: id_type::ResourceId,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, errors::StorageError> {+ self.diesel_store.find_linked_resource_by_id(id, key).await+ }++ async fn find_resource_scope_id(+ &self,+ id: id_type::ResourceId,+ ) -> CustomResult<String, errors::StorageError> {+ self.diesel_store.find_resource_scope_id(id).await+ }++ async fn list_linked_resources_by_scope_id_and_resource_type(+ &self,+ scope_id: String,+ resource_type: String,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<Vec<domain::HierarchicalResource>, errors::StorageError> {+ self.diesel_store+ .list_linked_resources_by_scope_id_and_resource_type(scope_id, resource_type, key)+ .await+ }++ async fn update_linked_resource_data(+ &self,+ id: id_type::ResourceId,+ update: domain::HierarchicalResourceDataUpdate,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, errors::StorageError> {+ self.diesel_store+ .update_linked_resource_data(id, update, key)+ .await+ }+}+#[async_trait::async_trait]impl ProfileInterface for KafkaStore {type Error = errors::StorageError;diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rsindex c934e17a8b..b39757279b 100644--- a/crates/router/src/lib.rs+++ b/crates/router/src/lib.rs@@ -266,6 +266,10 @@ pub fn mk_app(server_app = server_app.service(routes::Profile::server(state.clone()));}+ #[cfg(all(feature = "olap", feature = "v1"))]+ {+ server_app = server_app.service(routes::HierarchicalResources::server(state.clone()));+ }server_app = server_app.service(routes::Payments::server(state.clone())).service(routes::Customers::server(state.clone()))diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rsindex 9c32269ff6..d4059579bd 100644--- a/crates/router/src/routes.rs+++ b/crates/router/src/routes.rs@@ -79,6 +79,9 @@ pub mod recovery_webhooks;pub mod relay;+#[cfg(all(feature = "olap", feature = "v1"))]+pub mod hierarchical_resources;+#[cfg(feature = "olap")]pub mod process_tracker;@@ -102,7 +105,8 @@ pub use self::app::{};#[cfg(feature = "olap")]pub use self::app::{- Blocklist, Organization, Routing, Subscription, UnifiedConnectorService, Verify, WebhookEvents,+ Blocklist, HierarchicalResources, Organization, Routing, Subscription, UnifiedConnectorService,+ Verify, WebhookEvents,};#[cfg(feature = "payouts")]pub use self::app::{PayoutLink, Payouts};diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 1b85e58562..af5bc66643 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -2189,6 +2189,34 @@ impl MerchantConnectorAccount {}}+pub struct HierarchicalResources;++#[cfg(all(feature = "olap", feature = "v1"))]+impl HierarchicalResources {+ pub fn server(state: AppState) -> Scope {+ web::scope("/hierarchical_resources")+ .app_data(web::Data::new(state))+ .service(web::resource("").route(+ web::post().to(super::hierarchical_resources::generate_hierarchical_resource),+ ))+ .service(+ web::resource("/list").route(+ web::post().to(super::hierarchical_resources::list_hierarchical_resources),+ ),+ )+ .service(+ web::resource("/apple_pay_certificate/{resource_id}").route(+ web::put().to(super::hierarchical_resources::upload_hierarchical_resource),+ ),+ )+ .service(+ web::resource("/{resource_id}/link").route(+ web::post().to(super::hierarchical_resources::link_hierarchical_resource),+ ),+ )+ }+}+pub struct EphemeralKey;#[cfg(all(feature = "v1", feature = "oltp"))]diff --git a/crates/router/src/routes/hierarchical_resources.rs b/crates/router/src/routes/hierarchical_resources.rsnew file mode 100644index 0000000000..45a783d754--- /dev/null+++ b/crates/router/src/routes/hierarchical_resources.rs@@ -0,0 +1,242 @@+use actix_web::{http::header, web, HttpRequest, HttpResponse};+use api_models::hierarchical_resources as api_resources;+use base64::Engine;+use common_utils::id_type;+use error_stack::ResultExt;+use router_env::{instrument, tracing, Flow};++use super::app::{AppState, SessionState};+use crate::{+ core::{api_locking, errors, hierarchical_resources as resources_core},+ headers,+ services::{+ api, authentication as auth, authentication::HeaderMapStruct,+ authorization::permissions::Permission,+ },+};++/// `/resources` is JWT-only (dashboard session) and mandates `X-Profile-Id`, resolving the+/// `Profile` the same way `ApiKeyAuth`/`payment_methods_session_create` do — the fetch itself,+/// scoped to the JWT-authenticated merchant, is the authorization check: a `NotFound` means the+/// header names a profile that doesn't belong to this session's merchant.+fn mandatory_profile_id_from_header(req: &HttpRequest) -> Result<id_type::ProfileId, HttpResponse> {+ HeaderMapStruct::new(req.headers())+ .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)+ .map_err(api::log_and_return_error_response)+}++async fn resolve_profile_from_header(+ state: &SessionState,+ auth_data: &auth::AuthenticationData,+ profile_id: &id_type::ProfileId,+) -> Result<crate::types::domain::Profile, error_stack::Report<errors::ApiErrorResponse>> {+ let processor = auth_data.platform.get_processor();+ state+ .store+ .find_business_profile_by_merchant_id_profile_id(+ processor.get_key_store(),+ processor.get_account().get_id(),+ profile_id,+ )+ .await+ .change_context(errors::ApiErrorResponse::Unauthorized)+ .attach_printable(+ "X-Profile-Id does not name a profile belonging to this session's merchant",+ )+}++fn parse_upload_certificate_body(+ req: &HttpRequest,+ body: &[u8],+) -> Result<api_resources::UploadCertificateRequest, HttpResponse> {+ let is_json = req+ .headers()+ .get(header::CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .is_some_and(|value| value.starts_with(mime::APPLICATION_JSON.as_ref()));++ if is_json {+ serde_json::from_slice(body).map_err(|error| {+ api::log_and_return_error_response(error_stack::report!(+ errors::ApiErrorResponse::InvalidRequestData {+ message: format!("invalid JSON body: {error}"),+ }+ ))+ })+ } else {+ Ok(api_resources::UploadCertificateRequest {+ certificate: crate::consts::BASE64_ENGINE.encode(body),+ })+ }+}++#[instrument(skip_all, fields(flow = ?Flow::HierarchicalResourcesGenerate))]+pub async fn generate_hierarchical_resource(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<api_resources::GenerateHierarchicalResourceRequest>,+) -> HttpResponse {+ let flow = Flow::HierarchicalResourcesGenerate;+ let payload = json_payload.into_inner();+ let profile_id = match mandatory_profile_id_from_header(&req) {+ Ok(id) => id,+ Err(error_response) => return error_response,+ };+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ move |state, auth_data: auth::AuthenticationData, req, _| {+ let profile_id = profile_id.clone();+ async move {+ resolve_profile_from_header(&state, &auth_data, &profile_id).await?;+ resources_core::generate_hierarchical_resource(+ state,+ auth_data.platform.get_processor().clone(),+ req,+ )+ .await+ }+ },+ &auth::JWTAndEmbeddedAuth {+ merchant_id_from_route: None,+ permission: Some(Permission::MerchantConnectorWrite),+ allow_connected: true,+ allow_platform: true,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++#[instrument(skip_all, fields(flow = ?Flow::HierarchicalResourcesUpload))]+pub async fn upload_hierarchical_resource(+ state: web::Data<AppState>,+ req: HttpRequest,+ path: web::Path<id_type::ResourceId>,+ body: web::Bytes,+) -> HttpResponse {+ let flow = Flow::HierarchicalResourcesUpload;+ let payload = match parse_upload_certificate_body(&req, &body) {+ Ok(payload) => payload,+ Err(error_response) => return error_response,+ };+ let resource_id = path.into_inner();+ let profile_id = match mandatory_profile_id_from_header(&req) {+ Ok(id) => id,+ Err(error_response) => return error_response,+ };+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ move |state, auth_data: auth::AuthenticationData, req, _| {+ let resource_id = resource_id.clone();+ let profile_id = profile_id.clone();+ async move {+ resolve_profile_from_header(&state, &auth_data, &profile_id).await?;+ resources_core::upload_hierarchical_resource(+ state,+ auth_data.platform.get_processor().clone(),+ resource_id,+ req,+ )+ .await+ }+ },+ &auth::JWTAndEmbeddedAuth {+ merchant_id_from_route: None,+ permission: Some(Permission::MerchantConnectorWrite),+ allow_connected: true,+ allow_platform: true,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++#[instrument(skip_all, fields(flow = ?Flow::HierarchicalResourcesList))]+pub async fn list_hierarchical_resources(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<api_resources::ListHierarchicalResourcesRequest>,+) -> HttpResponse {+ let flow = Flow::HierarchicalResourcesList;+ let payload = json_payload.into_inner();+ let profile_id = match mandatory_profile_id_from_header(&req) {+ Ok(id) => id,+ Err(error_response) => return error_response,+ };+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ move |state, auth_data: auth::AuthenticationData, req, _| {+ let profile_id = profile_id.clone();+ async move {+ resolve_profile_from_header(&state, &auth_data, &profile_id).await?;+ resources_core::list_hierarchical_resources(+ state,+ auth_data.platform.get_processor().clone(),+ req,+ )+ .await+ }+ },+ &auth::JWTAndEmbeddedAuth {+ merchant_id_from_route: None,+ permission: Some(Permission::MerchantConnectorRead),+ allow_connected: true,+ allow_platform: true,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++#[instrument(skip_all, fields(flow = ?Flow::HierarchicalResourcesLink))]+pub async fn link_hierarchical_resource(+ state: web::Data<AppState>,+ req: HttpRequest,+ path: web::Path<id_type::ResourceId>,+ json_payload: web::Json<api_resources::LinkHierarchicalResourceRequest>,+) -> HttpResponse {+ let flow = Flow::HierarchicalResourcesLink;+ let payload = json_payload.into_inner();+ let resource_id = path.into_inner();+ let profile_id = match mandatory_profile_id_from_header(&req) {+ Ok(id) => id,+ Err(error_response) => return error_response,+ };+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ move |state, auth_data: auth::AuthenticationData, req, _| {+ let resource_id = resource_id.clone();+ let profile_id = profile_id.clone();+ async move {+ resolve_profile_from_header(&state, &auth_data, &profile_id).await?;+ resources_core::link_hierarchical_resource(+ state,+ auth_data.platform.get_processor().clone(),+ resource_id,+ req,+ )+ .await+ }+ },+ &auth::JWTAndEmbeddedAuth {+ merchant_id_from_route: None,+ permission: Some(Permission::MerchantConnectorWrite),+ allow_connected: true,+ allow_platform: true,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+}diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex 0627b3a738..e3f9683427 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -54,6 +54,7 @@ pub enum ApiIdentifier {RecoveryRecovery,Superposition,CardIssuers,+ HierarchicalResources,}impl From<Flow> for ApiIdentifier {@@ -70,6 +71,10 @@ impl From<Flow> for ApiIdentifier {| Flow::OrganizationRetrieve| Flow::OrganizationUpdate| Flow::ConvertOrganizationToPlatform => Self::Organization,+ Flow::HierarchicalResourcesGenerate+ | Flow::HierarchicalResourcesUpload+ | Flow::HierarchicalResourcesList+ | Flow::HierarchicalResourcesLink => Self::HierarchicalResources,Flow::RoutingCreateConfig| Flow::RoutingLinkConfig| Flow::RoutingUnlinkConfigdiff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rsindex 16dbb7d0e5..27dc701011 100644--- a/crates/router/src/types/domain.rs+++ b/crates/router/src/types/domain.rs@@ -49,6 +49,11 @@ mod merchant_connector_account;mod merchant_key_store {pub use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;}+mod hierarchical_resource {+ pub use hyperswitch_domain_models::hierarchical_resource::{+ HierarchicalResource, HierarchicalResourceDataUpdate,+ };+}pub use hyperswitch_domain_models::bulk_tokenization::*;pub mod payment_methods {pub use hyperswitch_domain_models::payment_methods::*;@@ -94,6 +99,7 @@ pub use business_profile::*;pub use callback_mapper::*;pub use consts::*;pub use event::*;+pub use hierarchical_resource::*;pub use merchant_connector_account::*;pub use merchant_connector_webhook_management::*;pub use merchant_key_store::*;diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 307e73dc0b..30805a1f94 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -92,6 +92,14 @@ pub enum Flow {MerchantConnectorsUpdate,/// Merchant Connectors delete flow.MerchantConnectorsDelete,+ /// Generate a hierarchical resource (e.g. Apple Pay certificate CSR) flow.+ HierarchicalResourcesGenerate,+ /// Upload a hierarchical resource's signed certificate flow.+ HierarchicalResourcesUpload,+ /// List hierarchical resources / get effective linked value flow.+ HierarchicalResourcesList,+ /// Link a hierarchical resource to an entity (MCA/profile/merchant_account) flow.+ HierarchicalResourcesLink,/// Merchant Connectors list flow.MerchantConnectorsList,/// Merchant Transfer Keysdiff --git a/crates/storage_impl/src/business_profile.rs b/crates/storage_impl/src/business_profile.rsindex b9ddc8cb6f..6dc4201067 100644--- a/crates/storage_impl/src/business_profile.rs+++ b/crates/storage_impl/src/business_profile.rs@@ -726,6 +726,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {.map(Encryption::from),payment_method_blocking,default_fallback_routing: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,}}domain::ProfileUpdate::RoutingAlgorithmUpdate {@@ -793,6 +795,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {network_tokenization_credentials: None,payment_method_blocking: None,default_fallback_routing: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::DynamicRoutingAlgorithmUpdate {dynamic_routing_algorithm,@@ -857,6 +861,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {network_tokenization_credentials: None,payment_method_blocking: None,default_fallback_routing: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::ExtendedCardInfoUpdate {is_extended_card_info_enabled,@@ -921,6 +927,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {network_tokenization_credentials: None,payment_method_blocking: None,default_fallback_routing: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::ConnectorAgnosticMitUpdate {is_connector_agnostic_mit_enabled,@@ -985,6 +993,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {network_tokenization_credentials: None,payment_method_blocking: None,default_fallback_routing: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::NetworkTokenizationUpdate {is_network_tokenization_enabled,@@ -1051,6 +1061,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {.map(Encryption::from),payment_method_blocking: None,default_fallback_routing: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::CardTestingSecretKeyUpdate {card_testing_secret_key,@@ -1115,6 +1127,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {network_tokenization_credentials: None,payment_method_blocking: None,default_fallback_routing: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::AcquirerConfigBucketUpdate {acquirer_config_map,@@ -1180,6 +1194,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {network_tokenization_credentials: None,payment_method_blocking: None,default_fallback_routing: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::DefaultRoutingFallbackUpdate {default_fallback_routing,@@ -1244,6 +1260,75 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {payment_method_blocking: None,default_fallback_routing,network_tokenization_credentials: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,+ },+ domain::ProfileUpdate::ApplePayCertificateCacheUpdate {+ apple_pay_certificates,+ apple_pay_certificates_encrypted,+ } => Self {+ profile_name: None,+ modified_at: now,+ return_url: None,+ enable_payment_response_hash: None,+ payment_response_hash_key: None,+ redirect_to_merchant_with_http_post: None,+ webhook_details: None,+ metadata: None,+ routing_algorithm: None,+ intent_fulfillment_time: None,+ order_fulfillment_time: None,+ frm_routing_algorithm: None,+ payout_routing_algorithm: None,+ is_recon_enabled: None,+ applepay_verified_domains: None,+ payment_link_config: None,+ session_expiry: None,+ authentication_connector_details: None,+ payout_link_config: None,+ is_extended_card_info_enabled: None,+ extended_card_info_config: None,+ is_connector_agnostic_mit_enabled: None,+ use_billing_as_payment_method_billing: None,+ collect_shipping_details_from_wallet_connector: None,+ collect_billing_details_from_wallet_connector: None,+ outgoing_webhook_custom_http_headers: None,+ always_collect_billing_details_from_wallet_connector: None,+ always_collect_shipping_details_from_wallet_connector: None,+ tax_connector_id: None,+ is_tax_connector_enabled: None,+ dynamic_routing_algorithm: None,+ is_network_tokenization_enabled: None,+ is_auto_retries_enabled: None,+ max_auto_retries_enabled: None,+ always_request_extended_authorization: None,+ is_click_to_pay_enabled: None,+ authentication_product_ids: None,+ card_testing_guard_config: None,+ card_testing_secret_key: None,+ is_clear_pan_retries_enabled: None,+ force_3ds_challenge: None,+ is_debit_routing_enabled: None,+ merchant_business_country: None,+ is_iframe_redirection_enabled: None,+ is_pre_network_tokenization_enabled: None,+ three_ds_decision_rule_algorithm: None,+ acquirer_config_map: None,+ merchant_category_code: None,+ merchant_country_code: None,+ dispute_polling_interval: None,+ is_manual_retry_enabled: None,+ always_enable_overcapture: None,+ is_external_vault_enabled: None,+ external_vault_connector_details: None,+ billing_processor_id: None,+ surcharge_connector_details: None,+ is_l2_l3_enabled: None,+ payment_method_blocking: None,+ default_fallback_routing: None,+ network_tokenization_credentials: None,+ apple_pay_certificates,+ apple_pay_certificates_encrypted,},}}@@ -1335,6 +1420,10 @@ impl Conversion for domain::Profile {.map(|name| name.into()),payment_method_blocking: self.payment_method_blocking,default_fallback_routing: self.default_fallback_routing,+ apple_pay_certificates: self.apple_pay_certificates,+ apple_pay_certificates_encrypted: self+ .apple_pay_certificates_encrypted+ .map(|data| data.into()),})}@@ -1352,6 +1441,7 @@ impl Conversion for domain::Profile {outgoing_webhook_custom_http_headers,card_testing_secret_key,network_tokenization_credentials,+ apple_pay_certificates_encrypted,) = async {let outgoing_webhook_custom_http_headers = item.outgoing_webhook_custom_http_headers@@ -1398,10 +1488,26 @@ impl Conversion for domain::Profile {}).await?;+ let apple_pay_certificates_encrypted = item+ .apple_pay_certificates_encrypted+ .async_lift(|inner| async {+ crypto_operation(+ state,+ type_name!(Self::DstType),+ CryptoOperation::DecryptOptional(inner),+ key_manager_identifier.clone(),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await?;+Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>((outgoing_webhook_custom_http_headers,card_testing_secret_key,network_tokenization_credentials,+ apple_pay_certificates_encrypted,))}.await@@ -1486,6 +1592,8 @@ impl Conversion for domain::Profile {network_tokenization_credentials,payment_method_blocking: item.payment_method_blocking,default_fallback_routing: item.default_fallback_routing,+ apple_pay_certificates: item.apple_pay_certificates,+ apple_pay_certificates_encrypted,}.into())}@@ -1671,6 +1779,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled,billing_processor_id,surcharge_connector_details,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,}}domain::ProfileUpdate::RoutingAlgorithmUpdate {@@ -1731,6 +1841,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled: None,billing_processor_id: None,surcharge_connector_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::ExtendedCardInfoUpdate {is_extended_card_info_enabled,@@ -1789,6 +1901,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled: None,billing_processor_id: None,surcharge_connector_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::ConnectorAgnosticMitUpdate {is_connector_agnostic_mit_enabled,@@ -1847,6 +1961,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled: None,billing_processor_id: None,surcharge_connector_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::DefaultRoutingFallbackUpdate {default_fallback_routing,@@ -1905,6 +2021,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled: None,billing_processor_id: None,surcharge_connector_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::NetworkTokenizationUpdate {is_network_tokenization_enabled,@@ -1963,6 +2081,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled: None,billing_processor_id: None,surcharge_connector_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::CollectCvvDuringPaymentUpdate {should_collect_cvv_during_payment,@@ -2021,6 +2141,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled: None,billing_processor_id: None,surcharge_connector_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::DecisionManagerRecordUpdate {three_ds_decision_manager_config,@@ -2079,6 +2201,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled: None,billing_processor_id: None,surcharge_connector_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::CardTestingSecretKeyUpdate {card_testing_secret_key,@@ -2137,6 +2261,8 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled: None,billing_processor_id: None,surcharge_connector_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::ProfileUpdate::RevenueRecoveryAlgorithmUpdate {revenue_recovery_retry_algorithm_type,@@ -2196,6 +2322,69 @@ impl ForeignFrom<domain::ProfileUpdate> for ProfileUpdateInternal {split_txns_enabled: None,billing_processor_id: None,surcharge_connector_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,+ },+ domain::ProfileUpdate::ApplePayCertificateCacheUpdate {+ apple_pay_certificates,+ apple_pay_certificates_encrypted,+ } => Self {+ profile_name: None,+ modified_at: now,+ return_url: None,+ enable_payment_response_hash: None,+ payment_response_hash_key: None,+ redirect_to_merchant_with_http_post: None,+ webhook_details: None,+ metadata: None,+ is_recon_enabled: None,+ applepay_verified_domains: None,+ payment_link_config: None,+ session_expiry: None,+ authentication_connector_details: None,+ payout_link_config: None,+ is_extended_card_info_enabled: None,+ extended_card_info_config: None,+ is_connector_agnostic_mit_enabled: None,+ use_billing_as_payment_method_billing: None,+ collect_shipping_details_from_wallet_connector: None,+ collect_billing_details_from_wallet_connector: None,+ outgoing_webhook_custom_http_headers: None,+ always_collect_billing_details_from_wallet_connector: None,+ always_collect_shipping_details_from_wallet_connector: None,+ routing_algorithm_id: None,+ is_l2_l3_enabled: None,+ payout_routing_algorithm_id: None,+ order_fulfillment_time: None,+ order_fulfillment_time_origin: None,+ frm_routing_algorithm_id: None,+ default_fallback_routing: None,+ should_collect_cvv_during_payment: None,+ tax_connector_id: None,+ is_tax_connector_enabled: None,+ is_network_tokenization_enabled: None,+ is_auto_retries_enabled: None,+ max_auto_retries_enabled: None,+ is_click_to_pay_enabled: None,+ authentication_product_ids: None,+ three_ds_decision_manager_config: None,+ card_testing_guard_config: None,+ card_testing_secret_key: None,+ is_clear_pan_retries_enabled: None,+ is_debit_routing_enabled: None,+ merchant_business_country: None,+ revenue_recovery_retry_algorithm_type: None,+ revenue_recovery_retry_algorithm_data: None,+ is_iframe_redirection_enabled: None,+ is_external_vault_enabled: None,+ external_vault_connector_details: None,+ merchant_category_code: None,+ merchant_country_code: None,+ split_txns_enabled: None,+ billing_processor_id: None,+ surcharge_connector_details: None,+ apple_pay_certificates,+ apple_pay_certificates_encrypted,},}}@@ -2283,6 +2472,8 @@ impl Conversion for domain::Profile {surcharge_connector_details: self.surcharge_connector_details,network_tokenization_credentials: None,payment_method_blocking: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,})}diff --git a/crates/storage_impl/src/hierarchical_resource.rs b/crates/storage_impl/src/hierarchical_resource.rsnew file mode 100644index 0000000000..e958b69f76--- /dev/null+++ b/crates/storage_impl/src/hierarchical_resource.rs@@ -0,0 +1,348 @@+use error_stack::{report, ResultExt};+use hyperswitch_domain_models::{+ behaviour::{Conversion, ReverseConversion},+ hierarchical_resource as domain,+ hierarchical_resource::HierarchicalResourceInterface,+};+use hyperswitch_masking::Secret;+use router_env::{instrument, tracing};++use crate::{+ kv_router_store,+ utils::{pg_accounts_connection_read, pg_accounts_connection_write},+ CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,+};++#[async_trait::async_trait]+impl<T: DatabaseStore> HierarchicalResourceInterface for kv_router_store::KVRouterStore<T> {+ type Error = StorageError;++ #[instrument(skip_all)]+ async fn insert_linked_resource(+ &self,+ resource: domain::HierarchicalResource,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, Self::Error> {+ self.router_store+ .insert_linked_resource(resource, key)+ .await+ }++ #[instrument(skip_all)]+ async fn find_linked_resource_by_id(+ &self,+ id: common_utils::id_type::ResourceId,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, Self::Error> {+ self.router_store.find_linked_resource_by_id(id, key).await+ }++ #[instrument(skip_all)]+ async fn find_resource_scope_id(+ &self,+ id: common_utils::id_type::ResourceId,+ ) -> CustomResult<String, Self::Error> {+ self.router_store.find_resource_scope_id(id).await+ }++ #[instrument(skip_all)]+ async fn list_linked_resources_by_scope_id_and_resource_type(+ &self,+ scope_id: String,+ resource_type: String,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<Vec<domain::HierarchicalResource>, Self::Error> {+ self.router_store+ .list_linked_resources_by_scope_id_and_resource_type(scope_id, resource_type, key)+ .await+ }++ #[instrument(skip_all)]+ async fn update_linked_resource_data(+ &self,+ id: common_utils::id_type::ResourceId,+ update: domain::HierarchicalResourceDataUpdate,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, Self::Error> {+ self.router_store+ .update_linked_resource_data(id, update, key)+ .await+ }+}++#[async_trait::async_trait]+impl<T: DatabaseStore> HierarchicalResourceInterface for RouterStore<T> {+ type Error = StorageError;++ #[instrument(skip_all)]+ async fn insert_linked_resource(+ &self,+ resource: domain::HierarchicalResource,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, Self::Error> {+ let conn = pg_accounts_connection_write(self).await?;+ let identifier = resource+ .key_identifier()+ .change_context(Self::Error::EncryptionError)?;+ resource+ .construct_new()+ .await+ .change_context(Self::Error::EncryptionError)?+ .insert(&conn)+ .await+ .map_err(|error| report!(Self::Error::from(error)))?+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key,+ identifier,+ )+ .await+ .change_context(Self::Error::DecryptionError)+ }++ #[instrument(skip_all)]+ async fn find_linked_resource_by_id(+ &self,+ id: common_utils::id_type::ResourceId,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, Self::Error> {+ let conn = pg_accounts_connection_read(self).await?;+ let resource =+ diesel_models::hierarchical_resource::HierarchicalResource::find_by_id(&conn, id)+ .await+ .map_err(|error| report!(Self::Error::from(error)))?;+ let identifier = domain::HierarchicalResource::identifier_for_diesel(&resource)+ .change_context(Self::Error::DecryptionError)?;++ resource+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key,+ identifier,+ )+ .await+ .change_context(Self::Error::DecryptionError)+ }++ #[instrument(skip_all)]+ async fn find_resource_scope_id(+ &self,+ id: common_utils::id_type::ResourceId,+ ) -> CustomResult<String, Self::Error> {+ let conn = pg_accounts_connection_read(self).await?;+ diesel_models::hierarchical_resource::HierarchicalResource::find_by_id(&conn, id)+ .await+ .map(|resource| resource.scope_id)+ .map_err(|error| report!(Self::Error::from(error)))+ }++ #[instrument(skip_all)]+ async fn list_linked_resources_by_scope_id_and_resource_type(+ &self,+ scope_id: String,+ resource_type: String,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<Vec<domain::HierarchicalResource>, Self::Error> {+ let conn = pg_accounts_connection_read(self).await?;+ let resources = diesel_models::hierarchical_resource::HierarchicalResource::list_by_scope_id_and_resource_type(+ &conn,+ scope_id,+ resource_type,+ )+ .await+ .map_err(|error| report!(Self::Error::from(error)))?;++ futures::future::try_join_all(resources.into_iter().map(|resource| async {+ let identifier = domain::HierarchicalResource::identifier_for_diesel(&resource)+ .change_context(Self::Error::DecryptionError)?;+ resource+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key,+ identifier,+ )+ .await+ .change_context(Self::Error::DecryptionError)+ }))+ .await+ }++ #[instrument(skip_all)]+ async fn update_linked_resource_data(+ &self,+ id: common_utils::id_type::ResourceId,+ update: domain::HierarchicalResourceDataUpdate,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, Self::Error> {+ let conn = pg_accounts_connection_write(self).await?;+ let resource = diesel_models::hierarchical_resource::HierarchicalResource::update_by_id(+ &conn,+ id,+ update.into(),+ )+ .await+ .map_err(|error| report!(Self::Error::from(error)))?;+ let identifier = domain::HierarchicalResource::identifier_for_diesel(&resource)+ .change_context(Self::Error::DecryptionError)?;++ resource+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key,+ identifier,+ )+ .await+ .change_context(Self::Error::DecryptionError)+ }+}++#[async_trait::async_trait]+impl HierarchicalResourceInterface for MockDb {+ type Error = StorageError;++ async fn insert_linked_resource(+ &self,+ resource: domain::HierarchicalResource,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, Self::Error> {+ let mut locked_resources = self.hierarchical_resources.lock().await;++ if locked_resources+ .iter()+ .any(|stored| stored.id == resource.id)+ {+ Err(StorageError::DuplicateValue {+ entity: "resources",+ key: Some(resource.id.get_string_repr().to_owned()),+ })?;+ }++ let identifier = resource+ .key_identifier()+ .change_context(StorageError::EncryptionError)?;+ let stored = Conversion::convert(resource)+ .await+ .change_context(StorageError::MockDbError)?;+ locked_resources.push(stored.clone());+ stored+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key,+ identifier,+ )+ .await+ .change_context(StorageError::DecryptionError)+ }++ async fn find_linked_resource_by_id(+ &self,+ id: common_utils::id_type::ResourceId,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, Self::Error> {+ let resource = self+ .hierarchical_resources+ .lock()+ .await+ .iter()+ .find(|stored| stored.id == id)+ .cloned()+ .ok_or(StorageError::ValueNotFound(String::from("resources")))?;+ let identifier = domain::HierarchicalResource::identifier_for_diesel(&resource)+ .change_context(StorageError::DecryptionError)?;++ resource+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key,+ identifier,+ )+ .await+ .change_context(StorageError::DecryptionError)+ }++ async fn find_resource_scope_id(+ &self,+ id: common_utils::id_type::ResourceId,+ ) -> CustomResult<String, Self::Error> {+ let scope_id = self+ .hierarchical_resources+ .lock()+ .await+ .iter()+ .find(|stored| stored.id == id)+ .map(|stored| stored.scope_id.clone())+ .ok_or(StorageError::ValueNotFound(String::from("resources")))?;+ Ok(scope_id)+ }++ async fn list_linked_resources_by_scope_id_and_resource_type(+ &self,+ scope_id: String,+ resource_type: String,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<Vec<domain::HierarchicalResource>, Self::Error> {+ let resources = self.hierarchical_resources.lock().await;+ futures::future::try_join_all(+ resources+ .iter()+ .filter(|stored| {+ stored.scope_id == scope_id && stored.resource_type == resource_type+ })+ .map(|stored| async {+ let identifier = domain::HierarchicalResource::identifier_for_diesel(stored)+ .change_context(StorageError::DecryptionError)?;+ stored+ .to_owned()+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key,+ identifier,+ )+ .await+ .change_context(StorageError::DecryptionError)+ }),+ )+ .await+ }++ async fn update_linked_resource_data(+ &self,+ id: common_utils::id_type::ResourceId,+ update: domain::HierarchicalResourceDataUpdate,+ key: &Secret<Vec<u8>>,+ ) -> CustomResult<domain::HierarchicalResource, Self::Error> {+ let mut locked_resources = self.hierarchical_resources.lock().await;+ let index = locked_resources+ .iter()+ .position(|stored| stored.id == id)+ .ok_or(StorageError::ValueNotFound(String::from("resources")))?;+ let update_internal: diesel_models::hierarchical_resource::HierarchicalResourceUpdateInternal = update.into();+ let entry = locked_resources+ .get_mut(index)+ .ok_or(StorageError::ValueNotFound(String::from("resources")))?;+ if let Some(data) = update_internal.data {+ entry.data = data;+ }+ entry.modified_at = update_internal.modified_at;+ let resource = entry.clone();+ let identifier = domain::HierarchicalResource::identifier_for_diesel(&resource)+ .change_context(StorageError::DecryptionError)?;++ resource+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key,+ identifier,+ )+ .await+ .change_context(StorageError::DecryptionError)+ }+}diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rsindex 3bf13c896f..a603885d84 100644--- a/crates/storage_impl/src/lib.rs+++ b/crates/storage_impl/src/lib.rs@@ -28,6 +28,7 @@ pub mod customers;pub mod database;pub mod dispute;pub mod errors;+pub mod hierarchical_resource;pub mod invoice;pub mod kv_router_store;pub mod lookup;diff --git a/crates/storage_impl/src/merchant_account.rs b/crates/storage_impl/src/merchant_account.rsindex 602ca00869..f2a4bfe65d 100644--- a/crates/storage_impl/src/merchant_account.rs+++ b/crates/storage_impl/src/merchant_account.rs@@ -933,6 +933,8 @@ impl ForeignFrom<domain::MerchantAccountUpdate> for MerchantAccountUpdateInternanetwork_tokenization_credentials: network_tokenization_credentials.map(Encryption::from),offer_engine_config: offer_engine_config.map(Encryption::from),+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {storage_scheme: Some(storage_scheme),@@ -964,6 +966,8 @@ impl ForeignFrom<domain::MerchantAccountUpdate> for MerchantAccountUpdateInternaproduct_type: None,network_tokenization_credentials: None,offer_engine_config: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::MerchantAccountUpdate::ReconUpdate { recon_status } => Self {recon_status: Some(recon_status),@@ -995,6 +999,8 @@ impl ForeignFrom<domain::MerchantAccountUpdate> for MerchantAccountUpdateInternaproduct_type: None,network_tokenization_credentials: None,offer_engine_config: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::MerchantAccountUpdate::UnsetDefaultProfile => Self {default_profile: Some(None),@@ -1026,6 +1032,8 @@ impl ForeignFrom<domain::MerchantAccountUpdate> for MerchantAccountUpdateInternaproduct_type: None,network_tokenization_credentials: None,offer_engine_config: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::MerchantAccountUpdate::ModifiedAtUpdate => Self {modified_at: now,@@ -1057,6 +1065,44 @@ impl ForeignFrom<domain::MerchantAccountUpdate> for MerchantAccountUpdateInternaproduct_type: None,network_tokenization_credentials: None,offer_engine_config: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,+ },+ domain::MerchantAccountUpdate::ApplePayCertificateCacheUpdate {+ apple_pay_certificates,+ apple_pay_certificates_encrypted,+ } => Self {+ modified_at: now,+ merchant_name: None,+ merchant_details: None,+ return_url: None,+ webhook_details: None,+ sub_merchants_enabled: None,+ parent_merchant_id: None,+ enable_payment_response_hash: None,+ payment_response_hash_key: None,+ redirect_to_merchant_with_http_post: None,+ publishable_key: None,+ storage_scheme: None,+ locker_id: None,+ metadata: None,+ routing_algorithm: None,+ primary_business_details: None,+ intent_fulfillment_time: None,+ frm_routing_algorithm: None,+ payout_routing_algorithm: None,+ organization_id: None,+ is_recon_enabled: None,+ default_profile: None,+ recon_status: None,+ payment_link_config: None,+ pm_collect_link_config: None,+ is_platform_account: None,+ product_type: None,+ network_tokenization_credentials: None,+ offer_engine_config: None,+ apple_pay_certificates,+ apple_pay_certificates_encrypted,},}}@@ -1084,6 +1130,8 @@ impl ForeignFrom<domain::MerchantAccountUpdate> for MerchantAccountUpdateInternarecon_status: None,is_platform_account: None,product_type: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {storage_scheme: Some(storage_scheme),@@ -1096,6 +1144,8 @@ impl ForeignFrom<domain::MerchantAccountUpdate> for MerchantAccountUpdateInternarecon_status: None,is_platform_account: None,product_type: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::MerchantAccountUpdate::ReconUpdate { recon_status } => Self {recon_status: Some(recon_status),@@ -1108,6 +1158,8 @@ impl ForeignFrom<domain::MerchantAccountUpdate> for MerchantAccountUpdateInternaorganization_id: None,is_platform_account: None,product_type: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,},domain::MerchantAccountUpdate::ModifiedAtUpdate => Self {modified_at: now,@@ -1120,6 +1172,25 @@ impl ForeignFrom<domain::MerchantAccountUpdate> for MerchantAccountUpdateInternarecon_status: None,is_platform_account: None,product_type: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,+ },+ domain::MerchantAccountUpdate::ApplePayCertificateCacheUpdate {+ apple_pay_certificates,+ apple_pay_certificates_encrypted,+ } => Self {+ modified_at: now,+ merchant_name: None,+ merchant_details: None,+ publishable_key: None,+ storage_scheme: None,+ metadata: None,+ organization_id: None,+ recon_status: None,+ is_platform_account: None,+ product_type: None,+ apple_pay_certificates,+ apple_pay_certificates_encrypted,},}}@@ -1401,6 +1472,21 @@ impl Conversion for domain::MerchantAccount {.and_then(|val| val.try_into_optionaloperation())}).await?,+ apple_pay_certificates: item.apple_pay_certificates,+ apple_pay_certificates_encrypted: item+ .apple_pay_certificates_encrypted+ .async_lift(|inner| async {+ crypto_operation(+ state,+ type_name!(Self::DstType),+ CryptoOperation::DecryptOptional(inner),+ key_manager_identifier.clone(),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await?,}.into(),)diff --git a/crates/storage_impl/src/merchant_connector_account.rs b/crates/storage_impl/src/merchant_connector_account.rsindex ec6c47e09f..7c44fbd251 100644--- a/crates/storage_impl/src/merchant_connector_account.rs+++ b/crates/storage_impl/src/merchant_connector_account.rs@@ -1378,6 +1378,8 @@ impl MerchantConnectorAccountInterface for MockDb {additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),version: t.version,connector_webhook_registration_details: t.connector_webhook_registration_details,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,};accounts.push(account.clone());account@@ -1421,6 +1423,8 @@ impl MerchantConnectorAccountInterface for MockDb {version: t.version,feature_metadata: t.feature_metadata.map(From::from),connector_webhook_registration_details: None,+ apple_pay_certificates: None,+ apple_pay_certificates_encrypted: None,};accounts.push(account.clone());accountdiff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rsindex 68cc782b7d..196c2e9f70 100644--- a/crates/storage_impl/src/mock_db.rs+++ b/crates/storage_impl/src/mock_db.rs@@ -45,6 +45,7 @@ pub struct MockDb {pub mandates: Arc<Mutex<Vec<store::Mandate>>>,pub captures: Arc<Mutex<Vec<store::capture::Capture>>>,pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>,+ pub hierarchical_resources: Arc<Mutex<Vec<store::hierarchical_resource::HierarchicalResource>>>,#[cfg(all(feature = "v2", feature = "tokenization_v2"))]pub tokenizations: Arc<Mutex<Vec<store::tokenization::Tokenization>>>,pub business_profiles: Arc<Mutex<Vec<store::business_profile::Profile>>>,@@ -106,6 +107,7 @@ impl MockDb {mandates: Default::default(),captures: Default::default(),merchant_key_store: Default::default(),+ hierarchical_resources: Default::default(),#[cfg(all(feature = "v2", feature = "tokenization_v2"))]tokenizations: Default::default(),business_profiles: Default::default(),diff --git a/migrations/2026-09-09-100000_create_hierarchical_resources_table/down.sql b/migrations/2026-09-09-100000_create_hierarchical_resources_table/down.sqlnew file mode 100644index 0000000000..d0b513bfc9--- /dev/null+++ b/migrations/2026-09-09-100000_create_hierarchical_resources_table/down.sql@@ -0,0 +1,2 @@+DROP INDEX IF EXISTS hierarchical_resources_scope_id_resource_type_index;+DROP TABLE IF EXISTS hierarchical_resources;diff --git a/migrations/2026-09-09-100000_create_hierarchical_resources_table/up.sql b/migrations/2026-09-09-100000_create_hierarchical_resources_table/up.sqlnew file mode 100644index 0000000000..fe12a6a5b2--- /dev/null+++ b/migrations/2026-09-09-100000_create_hierarchical_resources_table/up.sql@@ -0,0 +1,13 @@+CREATE TABLE hierarchical_resources (+ id VARCHAR(64) NOT NULL PRIMARY KEY,+ resource_type VARCHAR(64) NOT NULL,+ scope VARCHAR(32) NOT NULL,+ scope_id VARCHAR(64) NOT NULL,+ data JSONB NOT NULL,+ encrypted_data BYTEA,+ created_by TEXT NOT NULL,+ created_at TIMESTAMP NOT NULL,+ modified_at TIMESTAMP NOT NULL+);++CREATE INDEX hierarchical_resources_scope_id_resource_type_index ON hierarchical_resources (scope_id, resource_type);diff --git a/migrations/2026-09-09-150000_add_apple_pay_certificate_cache_columns/down.sql b/migrations/2026-09-09-150000_add_apple_pay_certificate_cache_columns/down.sqlnew file mode 100644index 0000000000..3aacef41b4--- /dev/null+++ b/migrations/2026-09-09-150000_add_apple_pay_certificate_cache_columns/down.sql@@ -0,0 +1,8 @@+ALTER TABLE merchant_account DROP COLUMN IF EXISTS apple_pay_certificates;+ALTER TABLE merchant_account DROP COLUMN IF EXISTS apple_pay_certificates_encrypted;++ALTER TABLE business_profile DROP COLUMN IF EXISTS apple_pay_certificates;+ALTER TABLE business_profile DROP COLUMN IF EXISTS apple_pay_certificates_encrypted;++ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS apple_pay_certificates;+ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS apple_pay_certificates_encrypted;diff --git a/migrations/2026-09-09-150000_add_apple_pay_certificate_cache_columns/up.sql b/migrations/2026-09-09-150000_add_apple_pay_certificate_cache_columns/up.sqlnew file mode 100644index 0000000000..328206f2f8--- /dev/null+++ b/migrations/2026-09-09-150000_add_apple_pay_certificate_cache_columns/up.sql@@ -0,0 +1,8 @@+ALTER TABLE merchant_account ADD COLUMN apple_pay_certificates JSONB;+ALTER TABLE merchant_account ADD COLUMN apple_pay_certificates_encrypted BYTEA;++ALTER TABLE business_profile ADD COLUMN apple_pay_certificates JSONB;+ALTER TABLE business_profile ADD COLUMN apple_pay_certificates_encrypted BYTEA;++ALTER TABLE merchant_connector_account ADD COLUMN apple_pay_certificates JSONB;+ALTER TABLE merchant_connector_account ADD COLUMN apple_pay_certificates_encrypted BYTEA;