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(roles): Remove legacy recon Roles and product_type filter in `get_parent_group_info` (#11833)
Grovy-31702b8cd2f9bb7e
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.tomlindex 21748b709f..88bb9e8196 100644--- a/crates/api_models/Cargo.toml+++ b/crates/api_models/Cargo.toml@@ -13,8 +13,7 @@ dummy_connector = ["euclid/dummy_connector", "common_enums/dummy_connector"]payouts = ["common_enums/payouts"]frm = []olap = []-openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"]-recon = []+openapi = ["common_enums/openapi", "olap", "dummy_connector"]v1 = ["common_utils/v1"]v2 = ["common_types/v2", "common_utils/v2", "tokenization_v2", "dep:reqwest", "revenue_recovery"]dynamic_routing = []diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rsindex 4c3f5633a5..46ac4778fe 100644--- a/crates/api_models/src/events.rs+++ b/crates/api_models/src/events.rs@@ -9,8 +9,6 @@ mod locker_migration;pub mod payment;#[cfg(feature = "payouts")]pub mod payouts;-#[cfg(feature = "recon")]-pub mod recon;pub mod refund;#[cfg(feature = "v2")]pub mod revenue_recovery;diff --git a/crates/api_models/src/events/recon.rs b/crates/api_models/src/events/recon.rsdeleted file mode 100644index dd2dc44ef5..0000000000--- a/crates/api_models/src/events/recon.rs+++ /dev/null@@ -1,32 +0,0 @@-use common_utils::events::{ApiEventMetric, ApiEventsType};-use hyperswitch_masking::PeekInterface;--use crate::recon::{- ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest, VerifyTokenResponse,-};--impl ApiEventMetric for ReconUpdateMerchantRequest {- fn get_api_event_type(&self) -> Option<ApiEventsType> {- Some(ApiEventsType::Recon)- }-}--impl ApiEventMetric for ReconTokenResponse {- fn get_api_event_type(&self) -> Option<ApiEventsType> {- Some(ApiEventsType::Recon)- }-}--impl ApiEventMetric for ReconStatusResponse {- fn get_api_event_type(&self) -> Option<ApiEventsType> {- Some(ApiEventsType::Recon)- }-}--impl ApiEventMetric for VerifyTokenResponse {- fn get_api_event_type(&self) -> Option<ApiEventsType> {- Some(ApiEventsType::User {- user_id: self.user_email.peek().to_string(),- })- }-}diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rsindex ac1c582230..57336e5f95 100644--- a/crates/api_models/src/lib.rs+++ b/crates/api_models/src/lib.rs@@ -41,8 +41,6 @@ pub mod process_tracker;pub mod profile_acquirer;#[cfg(feature = "v2")]pub mod proxy;-#[cfg(feature = "recon")]-pub mod recon;pub mod refunds;pub mod relay;#[cfg(feature = "v2")]diff --git a/crates/api_models/src/recon.rs b/crates/api_models/src/recon.rsdeleted file mode 100644index 08c6ccccbd..0000000000--- a/crates/api_models/src/recon.rs+++ /dev/null@@ -1,28 +0,0 @@-use common_utils::{id_type, pii};-use hyperswitch_masking::Secret;--use crate::enums;--#[derive(serde::Deserialize, Debug, serde::Serialize)]-pub struct ReconUpdateMerchantRequest {- pub recon_status: enums::ReconStatus,- pub user_email: pii::Email,-}--#[derive(Debug, serde::Serialize)]-pub struct ReconTokenResponse {- pub token: Secret<String>,-}--#[derive(Debug, serde::Serialize)]-pub struct ReconStatusResponse {- pub recon_status: enums::ReconStatus,-}--#[derive(serde::Serialize, Debug)]-pub struct VerifyTokenResponse {- pub merchant_id: id_type::MerchantId,- pub user_email: pii::Email,- #[serde(skip_serializing_if = "Option::is_none")]- pub acl: Option<String>,-}diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rsindex b0cc9aa855..ddb91932e6 100644--- a/crates/api_models/src/user_role/role.rs+++ b/crates/api_models/src/user_role/role.rs@@ -1,5 +1,6 @@use common_enums::{- EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource, RoleScope,+ EntityType, MerchantProductType, ParentGroup, PermissionGroup, PermissionScope, Resource,+ RoleScope,};#[derive(Debug, serde::Deserialize, serde::Serialize)]@@ -91,6 +92,7 @@ pub struct ListRolesAtEntityLevelRequest {#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct GetParentGroupsInfoQueryParams {pub entity_type: Option<EntityType>,+ pub product_type: Option<MerchantProductType>,}#[derive(Debug, serde::Deserialize, serde::Serialize)]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 6b3dfab0e5..46d5c06c3f 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -9521,10 +9521,6 @@ pub enum PermissionGroup {UsersManage,AccountView,AccountManage,- ReconReportsView,- ReconReportsManage,- ReconOpsView,- ReconOpsManage,InternalManage,ThemeView,ThemeManage,@@ -9547,8 +9543,6 @@ pub enum ParentGroup {Workflows,Analytics,Users,- ReconOps,- ReconReports,Account,Internal,Theme,@@ -9577,13 +9571,6 @@ pub enum Resource {WebhookEvent,Payout,Report,- ReconToken,- ReconFiles,- ReconAndSettlementAnalytics,- ReconUpload,- ReconReports,- RunRecon,- ReconConfig,RevenueRecovery,Subscription,InternalConnector,diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 13055581f9..3ab3bc7df2 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -21,7 +21,7 @@ encryption_service = ["keymanager_create", "hyperswitch_domain_models/encryptionkm_forward_x_request_id = ["common_utils/km_forward_x_request_id"]frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"]stripe = []-release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service", "dynamic_routing", "payout_retry"]+release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service", "dynamic_routing", "payout_retry"]oltp = ["storage_impl/oltp"]kv_store = ["scheduler/kv_store"]accounts_cache = ["storage_impl/accounts_cache"]@@ -30,7 +30,6 @@ dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "hypeexternal_access_dc = ["dummy_connector"]payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors/payouts", "hyperswitch_domain_models/payouts", "storage_impl/payouts", "payment_methods/payouts"]payout_retry = ["payouts"]-recon = ["email", "api_models/recon"]retry = []v2 = [ "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2", "hyperswitch_interfaces/v2", "common_types/v2", "revenue_recovery", "scheduler/v2", "euclid/v2", "payment_methods/v2", "tokenization_v2", "subscriptions/v2"]v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1", "scheduler/v1", "payment_link/v1", "payment_methods/v1", "subscriptions/v1", "analytics/v1"]diff --git a/crates/router/src/core.rs b/crates/router/src/core.rsindex 4e22a0403b..8a69fe5a10 100644--- a/crates/router/src/core.rs+++ b/crates/router/src/core.rs@@ -53,8 +53,6 @@ pub mod poll;pub mod profile_acquirer;#[cfg(feature = "v2")]pub mod proxy;-#[cfg(feature = "recon")]-pub mod recon;#[cfg(feature = "v1")]pub mod refunds;#[cfg(feature = "v2")]diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rsdeleted file mode 100644index b5a1cca394..0000000000--- a/crates/router/src/core/recon.rs+++ /dev/null@@ -1,262 +0,0 @@-use api_models::recon as recon_api;-#[cfg(feature = "email")]-use common_utils::{ext_traits::AsyncExt, types::user::ThemeLineage};-use error_stack::ResultExt;-#[cfg(feature = "email")]-use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};--#[cfg(feature = "email")]-use crate::{- consts, services::email::types as email_types, types::domain, utils::user::theme as theme_utils,-};-use crate::{- core::errors::{self, RouterResponse, UserErrors, UserResponse},- services::{api as service_api, authentication},- types::{- api::{self as api_types, enums},- storage,- transformers::ForeignTryFrom,- },- utils::user as user_utils,- SessionState,-};--#[allow(unused_variables)]-pub async fn send_recon_request(- state: SessionState,- auth_data: authentication::AuthenticationDataWithUser,-) -> RouterResponse<recon_api::ReconStatusResponse> {- #[cfg(not(feature = "email"))]- return Ok(service_api::ApplicationResponse::Json(- recon_api::ReconStatusResponse {- recon_status: enums::ReconStatus::NotRequested,- },- ));-- #[cfg(feature = "email")]- {- let user_in_db = &auth_data.user;- let merchant_id = auth_data.merchant_account.get_id().clone();-- let theme = theme_utils::get_most_specific_theme_using_lineage(- &state.clone(),- ThemeLineage::Merchant {- tenant_id: state.tenant.tenant_id.clone(),- org_id: auth_data.merchant_account.get_org_id().clone(),- merchant_id: merchant_id.clone(),- },- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(format!(- "Failed to fetch theme for merchant_id = {merchant_id:?}",- ))?;-- let user_email = user_in_db.email.clone();- let email_contents = email_types::ProFeatureRequest {- feature_name: consts::RECON_FEATURE_TAG.to_string(),- merchant_id: merchant_id.clone(),- user_name: domain::UserName::new(user_in_db.name.clone())- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to form username")?,- user_email: domain::UserEmail::from_pii_email(user_email.clone())- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to convert recipient's email to UserEmail")?,- recipient_email: domain::UserEmail::from_pii_email(- state.conf.email.recon_recipient_email.clone(),- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to convert recipient's email to UserEmail")?,- subject: format!(- "{} {}",- consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST,- user_email.expose().peek()- ),- theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),- theme_config: theme- .map(|theme| theme.email_config())- .unwrap_or(state.conf.theme.email_config.clone()),- };- state- .email_client- .compose_and_send_email(- user_utils::get_base_url(&state),- Box::new(email_contents),- state.conf.proxy.https_url.as_ref(),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]")- .async_and_then(|_| async {- let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate {- recon_status: enums::ReconStatus::Requested,- };- let db = &*state.store;-- let response = db- .update_merchant(- auth_data.merchant_account,- updated_merchant_account,- &auth_data.key_store,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable_lazy(|| {- format!("Failed while updating merchant's recon status: {merchant_id:?}")- })?;-- Ok(service_api::ApplicationResponse::Json(- recon_api::ReconStatusResponse {- recon_status: response.recon_status,- },- ))- })- .await- }-}--pub async fn generate_recon_token(- state: SessionState,- user_with_role: authentication::UserFromTokenWithRoleInfo,-) -> RouterResponse<recon_api::ReconTokenResponse> {- let user = user_with_role.user;- let token = authentication::ReconToken::new_token(- user.user_id.clone(),- user.merchant_id.clone(),- &state.conf,- user.org_id.clone(),- user.profile_id.clone(),- user.tenant_id,- user_with_role.role_info,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable_lazy(|| {- format!(- "Failed to create recon token for params [user_id, org_id, mid, pid] [{}, {:?}, {:?}, {:?}]",- user.user_id, user.org_id, user.merchant_id, user.profile_id,- )- })?;-- Ok(service_api::ApplicationResponse::Json(- recon_api::ReconTokenResponse {- token: token.into(),- },- ))-}--pub async fn recon_merchant_account_update(- state: SessionState,- processor: domain::Processor,- req: recon_api::ReconUpdateMerchantRequest,-) -> RouterResponse<api_types::MerchantAccountResponse> {- let db = &*state.store;-- let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate {- recon_status: req.recon_status,- };- let merchant_id = processor.get_account().get_id().clone();-- let updated_merchant_account = db- .update_merchant(- processor.get_account().clone(),- updated_merchant_account,- processor.get_key_store(),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable_lazy(|| {- format!("Failed while updating merchant's recon status: {merchant_id:?}")- })?;-- #[cfg(feature = "email")]- {- let user_email = &req.user_email.clone();-- let theme = theme_utils::get_most_specific_theme_using_lineage(- &state.clone(),- ThemeLineage::Merchant {- tenant_id: state.tenant.tenant_id.clone(),- org_id: processor.get_account().get_org_id().clone(),- merchant_id: merchant_id.clone(),- },- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(format!(- "Failed to fetch theme for merchant_id = {merchant_id:?}",- ))?;-- let email_contents = email_types::ReconActivation {- recipient_email: domain::UserEmail::from_pii_email(user_email.clone())- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to convert recipient's email to UserEmail from pii::Email",- )?,- user_name: domain::UserName::new(Secret::new("HyperSwitch User".to_string()))- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to form username")?,- subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST,- theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),- theme_config: theme- .map(|theme| theme.email_config())- .unwrap_or(state.conf.theme.email_config.clone()),- };- if req.recon_status == enums::ReconStatus::Active {- let _ = state- .email_client- .compose_and_send_email(- user_utils::get_base_url(&state),- Box::new(email_contents),- state.conf.proxy.https_url.as_ref(),- )- .await- .inspect_err(|err| {- router_env::logger::error!(- "Failed to compose and send email notifying them of recon activation: {}",- err- )- })- .change_context(UserErrors::InternalServerError)- .attach_printable("Failed to compose and send email for ReconActivation");- }- }-- Ok(service_api::ApplicationResponse::Json(- api_types::MerchantAccountResponse::foreign_try_from(updated_merchant_account)- .change_context(errors::ApiErrorResponse::InvalidDataValue {- field_name: "merchant_account",- })?,- ))-}--pub async fn verify_recon_token(- state: SessionState,- user_with_role: authentication::UserFromTokenWithRoleInfo,-) -> UserResponse<recon_api::VerifyTokenResponse> {- let user = user_with_role.user;- let user_in_db = user- .get_active_user_from_db(&state)- .await- .attach_printable_lazy(|| {- format!(- "Failed to fetch the user from DB for user_id - {}",- user.user_id- )- })?;-- let acl = user_with_role.role_info.get_recon_acl();- let optional_acl_str = serde_json::to_string(&acl)- .inspect_err(|err| router_env::logger::error!("Failed to serialize acl to string: {}", err))- .change_context(UserErrors::InternalServerError)- .attach_printable("Failed to serialize acl to string. Using empty ACL")- .ok();-- Ok(service_api::ApplicationResponse::Json(- recon_api::VerifyTokenResponse {- merchant_id: user.merchant_id.to_owned(),- user_email: user_in_db.0.email,- acl: optional_acl_str,- },- ))-}diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rsindex c3ab7b8449..7fc1dafe77 100644--- a/crates/router/src/core/user.rs+++ b/crates/router/src/core/user.rs@@ -738,36 +738,38 @@ async fn handle_invitation(.attach_printable(format!("role_id = {} is not invitable", request.role_id))?;}- match req_role_info.get_entity_type() {- EntityType::Tenant | EntityType::Organization => {}- EntityType::Merchant | EntityType::Profile => {- let merchant_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),- )- .await- .change_context(UserErrors::InternalServerError)- .attach_printable("Failed to retrieve merchant key store by merchant_id")?;+ if let Some(role_product_type_filter) = req_role_info.get_product_type_filter() {+ match req_role_info.get_entity_type() {+ EntityType::Tenant | EntityType::Organization => {}+ EntityType::Merchant | EntityType::Profile => {+ let merchant_key_store = state+ .store+ .get_merchant_key_store_by_merchant_id(+ &user_from_token.merchant_id,+ &state.store.get_master_key().to_vec().into(),+ )+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Failed to retrieve merchant key store by merchant_id")?;- let merchant_account = state- .store- .find_merchant_account_by_merchant_id(- &user_from_token.merchant_id,- &merchant_key_store,- )- .await- .to_not_found_response(UserErrors::MerchantIdNotFound)?;-- let merchant_product_type = merchant_account- .product_type- .unwrap_or(MerchantProductType::Orchestration);- if req_role_info.get_merchant_product_type() != merchant_product_type {- Err(report!(UserErrors::InvalidRoleId)).attach_printable(format!(- "role_id = {} is not for product_type = {}",- request.role_id, merchant_product_type- ))?;+ let merchant_account = state+ .store+ .find_merchant_account_by_merchant_id(+ &user_from_token.merchant_id,+ &merchant_key_store,+ )+ .await+ .to_not_found_response(UserErrors::MerchantIdNotFound)?;++ let merchant_product_type = merchant_account+ .product_type+ .unwrap_or(MerchantProductType::Orchestration);+ if role_product_type_filter != merchant_product_type {+ Err(report!(UserErrors::InvalidRoleId)).attach_printable(format!(+ "role_id = {} is not for product_type = {}",+ request.role_id, merchant_product_type+ ))?;+ }}}}diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rsindex f354cd4a0b..fb7c406133 100644--- a/crates/router/src/core/user_role.rs+++ b/crates/router/src/core/user_role.rs@@ -19,7 +19,10 @@ use router_env::logger;use crate::{core::errors::{StorageErrorExt, UserErrors, UserResponse},- db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},+ db::{+ domain::role::get_accessible_product_categories,+ user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},+ },routes::{app::ReqState, SessionState},services::{authentication as auth,@@ -117,26 +120,34 @@ pub async fn get_parent_group_info());}- let parent_groups =- ParentGroup::get_descriptions_for_groups(entity_type, PermissionGroup::iter().collect())- .unwrap_or_default()- .into_iter()- .map(- |(parent_group, description)| role_api::ParentGroupDescription {- name: parent_group.clone(),- description,- scopes: PermissionGroup::iter()- .filter_map(|group| {- (group.parent() == parent_group).then_some(group.scope())- })- // TODO: Remove this hashset conversion when merchant access- // and organization access groups are removed- .collect::<HashSet<_>>()- .into_iter()- .collect(),- },- )- .collect::<Vec<_>>();+ let permission_groups = if let Some(product_type) = request.product_type {+ let accessible_product_categories = get_accessible_product_categories(product_type);+ PermissionGroup::iter()+ .filter(|group| {+ accessible_product_categories.contains(&group.get_role_product_category())+ })+ .collect()+ } else {+ PermissionGroup::iter().collect()+ };++ let parent_groups = ParentGroup::get_descriptions_for_groups(entity_type, permission_groups)+ .unwrap_or_default()+ .into_iter()+ .map(+ |(parent_group, description)| role_api::ParentGroupDescription {+ name: parent_group.clone(),+ description,+ scopes: PermissionGroup::iter()+ .filter_map(|group| (group.parent() == parent_group).then_some(group.scope()))+ // TODO: Remove this hashset conversion when merchant access+ // and organization access groups are removed+ .collect::<HashSet<_>>()+ .into_iter()+ .collect(),+ },+ )+ .collect::<Vec<_>>();Ok(ApplicationResponse::Json(parent_groups))}diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rsindex 036500acac..0cd3b03c37 100644--- a/crates/router/src/core/user_role/role.rs+++ b/crates/router/src/core/user_role/role.rs@@ -591,6 +591,7 @@ pub async fn list_roles_with_info(.as_ref().unwrap_or(&state.tenant.tenant_id).to_owned();+ let merchant_id = user_from_token.merchant_id.clone();let custom_roles =match utils::user_role::get_min_entity(user_role_entity, request.entity_type)? {EntityType::Tenant | EntityType::Organization => state@@ -607,7 +608,7 @@ pub async fn list_roles_with_info(EntityType::Merchant => state.global_store.generic_list_roles_by_entity_type(- ListRolesByEntityPayload::Merchant(user_from_token.merchant_id),+ ListRolesByEntityPayload::Merchant(merchant_id),is_lineage_data_required,tenant_id,user_from_token.org_id,@@ -619,10 +620,7 @@ pub async fn list_roles_with_info(EntityType::Profile => state.global_store.generic_list_roles_by_entity_type(- ListRolesByEntityPayload::Profile(- user_from_token.merchant_id,- user_from_token.profile_id,- ),+ ListRolesByEntityPayload::Profile(merchant_id, user_from_token.profile_id),is_lineage_data_required,tenant_id,user_from_token.org_id,@@ -634,6 +632,42 @@ pub async fn list_roles_with_info(role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));+ if let Some(entity_type) = request.entity_type {+ match entity_type {+ EntityType::Tenant | EntityType::Organization => {}+ EntityType::Merchant | EntityType::Profile => {+ let merchant_key_store = state+ .store+ .get_merchant_key_store_by_merchant_id(+ &user_from_token.merchant_id,+ &state.store.get_master_key().to_vec().into(),+ )+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Failed to retrieve merchant key store by merchant_id")?;++ let merchant_account = state+ .store+ .find_merchant_account_by_merchant_id(+ &user_from_token.merchant_id,+ &merchant_key_store,+ )+ .await+ .to_not_found_response(UserErrors::MerchantIdNotFound)?;++ let product_type = merchant_account+ .product_type+ .unwrap_or(MerchantProductType::Orchestration);++ role_info_vec.retain(|role_info| {+ role_info+ .get_product_type_filter()+ .is_none_or(|merchant_product_type| merchant_product_type == product_type)+ });+ }+ }+ }+if request.groups == Some(true) {let list_role_info_response = role_info_vec.into_iter()@@ -802,7 +836,11 @@ pub async fn list_roles_at_entity_level(.unwrap_or(MerchantProductType::Orchestration)}).to_not_found_response(UserErrors::MerchantIdNotFound)?;- role_info_vec.retain(|role_info| role_info.get_merchant_product_type() == product_type);+ role_info_vec.retain(|role_info| {+ role_info+ .get_product_type_filter()+ .is_none_or(|merchant_product_type| merchant_product_type == product_type)+ });}}diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rsindex cb64b58d60..065b7a74f9 100644--- a/crates/router/src/lib.rs+++ b/crates/router/src/lib.rs@@ -260,11 +260,6 @@ pub fn mk_app(server_app = server_app.service(routes::Proxy::server(state.clone()));}- #[cfg(all(feature = "recon", feature = "v1"))]- {- server_app = server_app.service(routes::Recon::server(state.clone()));- }-server_app = server_app.service(routes::Cache::server(state.clone()));server_app = server_app.service(routes::Health::server(state.clone()));// Registered at the end because this entry has an empty scopediff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rsindex 569ccb44c7..68780c7ce5 100644--- a/crates/router/src/routes.rs+++ b/crates/router/src/routes.rs@@ -47,8 +47,6 @@ pub mod poll;pub mod profile_acquirer;#[cfg(feature = "olap")]pub mod profiles;-#[cfg(feature = "recon")]-pub mod recon;pub mod refunds;#[cfg(feature = "v2")]pub mod revenue_recovery_data_backfill;@@ -92,8 +90,6 @@ pub use self::app::DummyConnector;pub use self::app::PaymentMethodSession;#[cfg(all(feature = "oltp", feature = "v2"))]pub use self::app::Proxy;-#[cfg(all(feature = "olap", feature = "recon", feature = "v1"))]-pub use self::app::Recon;pub use self::app::{ApiKeys, AppState, ApplePayCertificatesMigration, Authentication, Cache, CardIssuers, Cards,Chat, Configs, ConnectorOnboarding, Customers, Disputes, Embedded, EphemeralKey, FeatureMatrix,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 8485aed744..570307c730 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -96,8 +96,6 @@ use crate::routes::feature_matrix;use crate::routes::fraud_check as frm_routes;#[cfg(all(feature = "olap", feature = "v1"))]use crate::routes::profile_acquirer;-#[cfg(all(feature = "recon", feature = "olap"))]-use crate::routes::recon as recon_routes;pub use crate::{configs::settings,db::{@@ -1801,29 +1799,6 @@ impl Tokenization {}}-#[cfg(all(feature = "olap", feature = "recon", feature = "v1"))]-pub struct Recon;--#[cfg(all(feature = "olap", feature = "recon", feature = "v1"))]-impl Recon {- pub fn server(state: AppState) -> Scope {- web::scope("/recon")- .app_data(web::Data::new(state))- .service(- web::resource("/{merchant_id}/update")- .route(web::post().to(recon_routes::update_merchant)),- )- .service(web::resource("/token").route(web::get().to(recon_routes::get_recon_token)))- .service(- web::resource("/request").route(web::post().to(recon_routes::request_for_recon)),- )- .service(- web::resource("/verify_token")- .route(web::get().to(recon_routes::verify_recon_token)),- )- }-}-pub struct Hypersense;impl Hypersense {diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex be4bed22fe..b49c070d69 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -36,7 +36,6 @@ pub enum ApiIdentifier {User,UserRole,ConnectorOnboarding,- Recon,AiWorkflow,Poll,ApplePayCertificatesMigration,@@ -351,10 +350,6 @@ impl From<Flow> for ApiIdentifier {Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => {Self::ConnectorOnboarding}- Flow::ReconMerchantUpdate- | Flow::ReconTokenRequest- | Flow::ReconServiceRequest- | Flow::ReconVerifyToken => Self::Recon,Flow::RetrievePollStatus => Self::Poll,Flow::FeatureMatrix => Self::Documentation,Flow::TokenizeCarddiff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rsdeleted file mode 100644index 1e1bdf44be..0000000000--- a/crates/router/src/routes/recon.rs+++ /dev/null@@ -1,87 +0,0 @@-use actix_web::{web, HttpRequest, HttpResponse};-use api_models::recon as recon_api;-use router_env::Flow;--use super::AppState;-use crate::{- core::{api_locking, recon},- services::{api, authentication, authorization::permissions::Permission},-};--pub async fn update_merchant(- state: web::Data<AppState>,- req: HttpRequest,- path: web::Path<common_utils::id_type::MerchantId>,- json_payload: web::Json<recon_api::ReconUpdateMerchantRequest>,-) -> HttpResponse {- let flow = Flow::ReconMerchantUpdate;- let merchant_id = path.into_inner();-- Box::pin(api::server_wrap(- flow,- state,- &req,- json_payload.into_inner(),- |state, auth: authentication::AuthenticationData, req, _| {- recon::recon_merchant_account_update(state, auth.platform.get_processor().clone(), req)- },- &authentication::AdminApiAuthWithMerchantIdFromRoute(merchant_id),- api_locking::LockAction::NotApplicable,- ))- .await-}--pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse {- let flow = Flow::ReconServiceRequest;- Box::pin(api::server_wrap(- flow,- state,- &http_req,- (),- |state, user, _, _| recon::send_recon_request(state, user),- &authentication::JWTAuth {- permission: Permission::MerchantAccountWrite,- allow_connected: true,- allow_platform: false,- },- api_locking::LockAction::NotApplicable,- ))- .await-}--pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {- let flow = Flow::ReconTokenRequest;- Box::pin(api::server_wrap(- flow,- state,- &req,- (),- |state, user, _, _| recon::generate_recon_token(state, user),- &authentication::JWTAuth {- permission: Permission::MerchantReconTokenRead,- allow_connected: true,- allow_platform: false,- },- api_locking::LockAction::NotApplicable,- ))- .await-}--#[cfg(feature = "recon")]-pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse {- let flow = Flow::ReconVerifyToken;- Box::pin(api::server_wrap(- flow,- state.clone(),- &http_req,- (),- |state, user, _req, _| recon::verify_recon_token(state, user),- &authentication::JWTAuth {- permission: Permission::MerchantReconTokenRead,- allow_connected: true,- allow_platform: false,- },- api_locking::LockAction::NotApplicable,- ))- .await-}diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rsindex acbd98e47e..4e7791e1aa 100644--- a/crates/router/src/routes/user.rs+++ b/crates/router/src/routes/user.rs@@ -1255,10 +1255,7 @@ pub async fn authorize_token(&http_req,json_payload.into_inner(),|state, _: (), payload, _| user_core::authorize_token(state, payload),- &auth::InternalMerchantIdProfileIdAuth(auth::DashboardNoPermissionAuth {- allow_connected: true,- allow_platform: true,- }),+ &auth::InternalMerchantIdProfileIdAuth(auth::NoAuth),api_locking::LockAction::NotApplicable,)).awaitdiff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 05b82d4194..606b18a39f 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -58,7 +58,7 @@ use crate::{headers,routes::app::SessionStateInfo,services::api,- types::{domain, storage},+ types::domain,utils::OptionExt,};@@ -133,25 +133,11 @@ pub struct AuthenticationDataWithMultipleProfiles {pub profile_id_list: Option<Vec<id_type::ProfileId>>,}-#[derive(Clone, Debug)]-pub struct AuthenticationDataWithUser {- pub merchant_account: domain::MerchantAccount,- pub key_store: domain::MerchantKeyStore,- pub user: storage::User,- pub profile_id: id_type::ProfileId,-}-#[derive(Clone, Debug)]pub struct AuthenticationDataWithOrg {pub organization_id: id_type::OrganizationId,}-#[derive(Clone)]-pub struct UserFromTokenWithRoleInfo {- pub user: UserFromToken,- pub role_info: authorization::roles::RoleInfo,-}-#[derive(Clone, Debug, Eq, PartialEq, Serialize)]#[serde(tag = "api_auth_type",@@ -6148,71 +6134,6 @@ wheredefault_auth}-#[cfg(feature = "recon")]-#[async_trait]-impl<A> AuthenticateAndFetch<AuthenticationDataWithUser, A> for JWTAuth-where- A: SessionStateInfo + Sync,-{- async fn authenticate_and_fetch(- &self,- request_headers: &HeaderMap,- state: &A,- ) -> RouterResult<(AuthenticationDataWithUser, AuthenticationType)> {- let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;- if payload.check_in_blacklist(state).await? {- return Err(errors::ApiErrorResponse::InvalidJwtToken.into());- }- authorization::check_tenant(- payload.tenant_id.clone(),- &state.session_state().tenant.tenant_id,- )?;- let role_info = authorization::get_role_info(state, &payload).await?;- authorization::check_permission(self.permission, &role_info)?;-- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )- .await- .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)- .attach_printable("Failed to fetch merchant key store for the merchant id")?;-- let merchant = state- .store()- .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store)- .await- .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)- .attach_printable("Failed to fetch merchant account for the merchant id")?;-- let user_id = payload.user_id;-- let user = state- .session_state()- .global_store- .find_active_user_by_user_id(&user_id)- .await- .to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)- .attach_printable("Failed to fetch user for the user id")?;-- let auth = AuthenticationDataWithUser {- merchant_account: merchant,- key_store,- profile_id: payload.profile_id.clone(),- user,- };-- let auth_type = AuthenticationType::MerchantJwt {- merchant_id: auth.merchant_account.get_id().clone(),- user_id: Some(user_id),- };-- Ok((auth, auth_type))- }-}-/// Validates whether the merchant account type is authorized to access the resource////// # Access Control Logic:@@ -6564,93 +6485,6 @@ fn throw_error_if_platform_merchant_authentication_required(})}-#[cfg(feature = "recon")]-#[async_trait]-impl<A> AuthenticateAndFetch<UserFromTokenWithRoleInfo, A> for JWTAuth-where- A: SessionStateInfo + Sync,-{- async fn authenticate_and_fetch(- &self,- request_headers: &HeaderMap,- state: &A,- ) -> RouterResult<(UserFromTokenWithRoleInfo, AuthenticationType)> {- let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;- if payload.check_in_blacklist(state).await? {- return Err(errors::ApiErrorResponse::InvalidJwtToken.into());- }- authorization::check_tenant(- payload.tenant_id.clone(),- &state.session_state().tenant.tenant_id,- )?;- let role_info = authorization::get_role_info(state, &payload).await?;- authorization::check_permission(self.permission, &role_info)?;-- let user = UserFromToken {- user_id: payload.user_id.clone(),- merchant_id: payload.merchant_id.clone(),- org_id: payload.org_id,- role_id: payload.role_id,- profile_id: payload.profile_id,- tenant_id: payload.tenant_id,- };-- Ok((- UserFromTokenWithRoleInfo { user, role_info },- AuthenticationType::MerchantJwt {- merchant_id: payload.merchant_id,- user_id: Some(payload.user_id),- },- ))- }-}--#[cfg(feature = "recon")]-#[derive(serde::Serialize, serde::Deserialize)]-pub struct ReconToken {- pub user_id: String,- pub merchant_id: id_type::MerchantId,- pub role_id: String,- pub exp: u64,- pub org_id: id_type::OrganizationId,- pub profile_id: id_type::ProfileId,- pub tenant_id: Option<id_type::TenantId>,- #[serde(skip_serializing_if = "Option::is_none")]- pub acl: Option<String>,-}--#[cfg(all(feature = "olap", feature = "recon"))]-impl ReconToken {- pub async fn new_token(- user_id: String,- merchant_id: id_type::MerchantId,- settings: &Settings,- org_id: id_type::OrganizationId,- profile_id: id_type::ProfileId,- tenant_id: Option<id_type::TenantId>,- role_info: authorization::roles::RoleInfo,- ) -> UserResult<String> {- let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);- let exp = jwt::generate_exp(exp_duration)?.as_secs();- let acl = role_info.get_recon_acl();- let optional_acl_str = serde_json::to_string(&acl)- .inspect_err(|err| logger::error!("Failed to serialize acl to string: {}", err))- .change_context(errors::UserErrors::InternalServerError)- .attach_printable("Failed to serialize acl to string. Using empty ACL")- .ok();- let token_payload = Self {- user_id,- merchant_id,- role_id: role_info.get_role_id().to_string(),- exp,- org_id,- profile_id,- tenant_id,- acl: optional_acl_str,- };- jwt::generate_jwt(&token_payload, settings).await- }-}#[derive(serde::Serialize, serde::Deserialize)]pub struct ExternalToken {pub user_id: String,diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rsindex dc70ac8def..37bd924fd0 100644--- a/crates/router/src/services/authorization/info.rs+++ b/crates/router/src/services/authorization/info.rs@@ -43,10 +43,6 @@ fn get_group_description(group: PermissionGroup) -> Option<&'static str> {PermissionGroup::UsersManage => Some("Manage and invite Users to the Team"),PermissionGroup::AccountView => Some("View Merchant Details"),PermissionGroup::AccountManage => Some("Create, modify and delete Merchant Details like api keys, webhooks, etc"),- PermissionGroup::ReconReportsView => Some("View reconciliation reports and analytics"),- PermissionGroup::ReconReportsManage => Some("Manage reconciliation reports"),- PermissionGroup::ReconOpsView => Some("View and access all reconciliation operations including reports and analytics"),- PermissionGroup::ReconOpsManage => Some("Manage all reconciliation operations including reports and analytics"),PermissionGroup::ThemeView => Some("View Themes"),PermissionGroup::ThemeManage => Some("Manage Themes"),PermissionGroup::InternalManage => None, // Internal group, no user-facing description@@ -69,8 +65,6 @@ pub fn get_parent_group_description(group: ParentGroup) -> Option<&'static str>ParentGroup::Analytics => Some("View Analytics"),ParentGroup::Users => Some("Manage and invite Users to the Team"),ParentGroup::Account => Some("Create, modify and delete Merchant Details like api keys, webhooks, etc"),- ParentGroup::ReconOps => Some("View, manage reconciliation operations like upload and process files, run reconciliation etc"),- ParentGroup::ReconReports => Some("View, manage reconciliation reports and analytics"),ParentGroup::Theme => Some("Manage and view themes for the organization"),ParentGroup::Internal => None, // Internal group, no user-facing descriptionParentGroup::ReconSources => Some("Recon ingestion and transformation pipelines"),diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rsindex 4e5545fc69..8fc6d54ee9 100644--- a/crates/router/src/services/authorization/permission_groups.rs+++ b/crates/router/src/services/authorization/permission_groups.rs@@ -23,8 +23,6 @@ impl PermissionGroupExt for PermissionGroup {| Self::AnalyticsView| Self::UsersView| Self::AccountView- | Self::ReconOpsView- | Self::ReconReportsView| Self::ThemeView| Self::ReconSourcesView| Self::ReconTransactionsView@@ -36,8 +34,6 @@ impl PermissionGroupExt for PermissionGroup {| Self::WorkflowsManage| Self::UsersManage| Self::AccountManage- | Self::ReconOpsManage- | Self::ReconReportsManage| Self::InternalManage| Self::ThemeManage| Self::ReconSourcesManage@@ -57,8 +53,6 @@ impl PermissionGroupExt for PermissionGroup {Self::AccountView | Self::AccountManage => ParentGroup::Account,Self::ThemeView | Self::ThemeManage => ParentGroup::Theme,- Self::ReconOpsView | Self::ReconOpsManage => ParentGroup::ReconOps,- Self::ReconReportsView | Self::ReconReportsManage => ParentGroup::ReconReports,Self::InternalManage => ParentGroup::Internal,Self::ReconSourcesView | Self::ReconSourcesManage => ParentGroup::ReconSources,Self::ReconExceptionsView | Self::ReconExceptionsManage => ParentGroup::ReconExceptions,@@ -99,12 +93,6 @@ impl PermissionGroupExt for PermissionGroup {vec![Self::UsersView, Self::UsersManage]}- Self::ReconOpsView => vec![Self::ReconOpsView],- Self::ReconOpsManage => vec![Self::ReconOpsView, Self::ReconOpsManage],-- Self::ReconReportsView => vec![Self::ReconReportsView],- Self::ReconReportsManage => vec![Self::ReconReportsView, Self::ReconReportsManage],-Self::AccountView => vec![Self::AccountView],Self::AccountManage => vec![Self::AccountView, Self::AccountManage],@@ -130,6 +118,7 @@ impl PermissionGroupExt for PermissionGroup {],Self::ReconExceptionsManage => vec![Self::ReconExceptionsManage,+ Self::ReconExceptionsView,Self::ReconTransactionsView,Self::ReconRulesView,],@@ -163,10 +152,6 @@ impl PermissionGroupExt for PermissionGroup {| Self::AnalyticsView| Self::AccountView| Self::AccountManage- | Self::ReconReportsView- | Self::ReconReportsManage- | Self::ReconOpsView- | Self::ReconOpsManage| Self::InternalManage| Self::ThemeView| Self::ThemeManage => RoleProductCategory::Orchestration,@@ -202,8 +187,6 @@ impl ParentGroupExt for ParentGroup {Self::Analytics => ANALYTICS.to_vec(),Self::Users => USERS.to_vec(),Self::Account => ACCOUNT.to_vec(),- Self::ReconOps => RECON_OPS.to_vec(),- Self::ReconReports => RECON_REPORTS.to_vec(),Self::Internal => INTERNAL.to_vec(),Self::Theme => THEME.to_vec(),Self::ReconSources => RECON_SOURCES.to_vec(),@@ -276,33 +259,22 @@ pub static USERS: [Resource; 2] = [Resource::User, Resource::Account];pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent];-pub static RECON_OPS: [Resource; 8] = [- Resource::ReconToken,- Resource::ReconFiles,- Resource::ReconUpload,- Resource::RunRecon,- Resource::ReconConfig,- Resource::ReconAndSettlementAnalytics,- Resource::ReconReports,- Resource::Account,-];-pub static INTERNAL: [Resource; 1] = [Resource::InternalConnector];-pub static RECON_REPORTS: [Resource; 4] = [- Resource::ReconToken,- Resource::ReconAndSettlementAnalytics,- Resource::ReconReports,- Resource::Account,-];-pub static THEME: [Resource; 1] = [Resource::Theme];-pub static RECON_SOURCES: [Resource; 2] = [Resource::ReconIngestion, Resource::ReconTransformation];+pub static RECON_SOURCES: [Resource; 3] = [+ Resource::ReconIngestion,+ Resource::ReconTransformation,+ Resource::Account,+];-pub static RECON_EXCEPTIONS: [Resource; 1] = [Resource::ReconException];+pub static RECON_EXCEPTIONS: [Resource; 2] = [Resource::ReconException, Resource::Account];-pub static RECON_TRANSACTIONS: [Resource; 2] =- [Resource::ReconStagingEntry, Resource::ReconTransaction];+pub static RECON_TRANSACTIONS: [Resource; 3] = [+ Resource::ReconStagingEntry,+ Resource::ReconTransaction,+ Resource::Account,+];-pub static RECON_RULES: [Resource; 1] = [Resource::ReconRule];+pub static RECON_RULES: [Resource; 2] = [Resource::ReconRule, Resource::Account];diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rsindex e5f1127c2a..142ed16b4f 100644--- a/crates/router/src/services/authorization/permissions.rs+++ b/crates/router/src/services/authorization/permissions.rs@@ -71,34 +71,6 @@ generate_permissions! {scopes: [Read, Write],entities: [Profile, Merchant]},- ReconToken: {- scopes: [Read],- entities: [Merchant]- },- ReconFiles: {- scopes: [Read, Write],- entities: [Merchant]- },- ReconAndSettlementAnalytics: {- scopes: [Read],- entities: [Merchant]- },- ReconUpload: {- scopes: [Read, Write],- entities: [Merchant]- },- ReconReports: {- scopes: [Read, Write],- entities: [Merchant]- },- RunRecon: {- scopes: [Read, Write],- entities: [Merchant]- },- ReconConfig: {- scopes: [Read, Write],- entities: [Merchant]- },RevenueRecovery: {scopes: [Read],entities: [Profile]@@ -159,13 +131,6 @@ pub fn get_resource_name(resource: Resource, entity_type: EntityType) -> Option<(Resource::Report, _) => Some("Operation Reports"),(Resource::User, _) => Some("Users"),(Resource::WebhookEvent, _) => Some("Webhook Events"),- (Resource::ReconUpload, _) => Some("Reconciliation File Upload"),- (Resource::RunRecon, _) => Some("Run Reconciliation Process"),- (Resource::ReconConfig, _) => Some("Reconciliation Configurations"),- (Resource::ReconToken, _) => Some("Generate & Verify Reconciliation Token"),- (Resource::ReconFiles, _) => Some("Reconciliation Process Manager"),- (Resource::ReconReports, _) => Some("Reconciliation Reports"),- (Resource::ReconAndSettlementAnalytics, _) => Some("Reconciliation Analytics"),(Resource::Account, EntityType::Profile) => Some("Business Profile Account"),(Resource::Account, EntityType::Merchant) => Some("Merchant Account"),(Resource::Account, EntityType::Organization) => Some("Organization Account"),diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rsindex c0cdc93671..264f1afbd9 100644--- a/crates/router/src/services/authorization/roles.rs+++ b/crates/router/src/services/authorization/roles.rs@@ -1,14 +1,8 @@-#[cfg(feature = "recon")]-use std::collections::HashMap;use std::collections::HashSet;-#[cfg(feature = "recon")]-use api_models::enums::ReconPermissionScope;use common_enums::{EntityType, MerchantProductType, PermissionGroup, Resource, RoleScope};use common_utils::{errors::CustomResult, id_type};-#[cfg(feature = "recon")]-use super::permission_groups::{RECON_OPS, RECON_REPORTS};use super::{permission_groups::PermissionGroupExt, permissions::Permission};use crate::{core::errors, routes::SessionState};@@ -25,7 +19,7 @@ pub struct RoleInfo {is_deletable: bool,is_updatable: bool,is_internal: bool,- merchant_product_type: MerchantProductType,+ product_type_filter: Option<MerchantProductType>,}impl RoleInfo {@@ -70,8 +64,14 @@ impl RoleInfo {self.is_updatable}- pub fn get_merchant_product_type(&self) -> MerchantProductType {- self.merchant_product_type+ pub fn get_product_type_filter(&self) -> Option<MerchantProductType> {+ match self.entity_type {+ EntityType::Organization | EntityType::Tenant => None,+ EntityType::Merchant | EntityType::Profile => Some(+ self.product_type_filter+ .unwrap_or(MerchantProductType::Orchestration),+ ),+ }}pub fn get_resources_set(&self) -> HashSet<Resource> {@@ -89,38 +89,6 @@ impl RoleInfo {})}- #[cfg(feature = "recon")]- pub fn get_recon_acl(&self) -> HashMap<Resource, ReconPermissionScope> {- let mut acl: HashMap<Resource, ReconPermissionScope> = HashMap::new();- let mut recon_resources = RECON_OPS.to_vec();- recon_resources.extend(RECON_REPORTS);- let recon_internal_resources = [Resource::ReconToken];- self.get_permission_groups()- .iter()- .for_each(|permission_group| {- permission_group.resources().iter().for_each(|resource| {- if recon_resources.contains(resource)- && !recon_internal_resources.contains(resource)- {- let scope = match resource {- Resource::ReconAndSettlementAnalytics => ReconPermissionScope::Read,- _ => ReconPermissionScope::from(permission_group.scope()),- };- acl.entry(*resource)- .and_modify(|curr_scope| {- *curr_scope = if (*curr_scope) < scope {- scope- } else {- *curr_scope- }- })- .or_insert(scope);- }- })- });- acl- }-pub fn from_predefined_roles(role_id: &str) -> Option<Self> {predefined_roles::PREDEFINED_ROLES.get(role_id).cloned()}@@ -181,9 +149,7 @@ impl From<diesel_models::role::Role> for RoleInfo {is_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: role- .merchant_product_type- .unwrap_or(MerchantProductType::Orchestration),+ product_type_filter: role.merchant_product_type,}}}diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rsindex feb0b238a6..57b9037a71 100644--- a/crates/router/src/services/authorization/roles/predefined_roles.rs+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs@@ -24,10 +24,14 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::UsersManage,PermissionGroup::AccountView,PermissionGroup::AccountManage,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconOpsManage,- PermissionGroup::ReconReportsView,- PermissionGroup::ReconReportsManage,+ PermissionGroup::ReconSourcesView,+ PermissionGroup::ReconSourcesManage,+ PermissionGroup::ReconExceptionsView,+ PermissionGroup::ReconExceptionsManage,+ PermissionGroup::ReconTransactionsView,+ PermissionGroup::ReconTransactionsManage,+ PermissionGroup::ReconRulesView,+ PermissionGroup::ReconRulesManage,],role_id: common_utils::consts::ROLE_ID_INTERNAL_ADMIN.to_string(),role_name: "internal_admin".to_string(),@@ -37,7 +41,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: false,is_updatable: false,is_internal: true,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: None,},);roles.insert(@@ -50,8 +54,10 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::AnalyticsView,PermissionGroup::UsersView,PermissionGroup::AccountView,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconReportsView,+ PermissionGroup::ReconSourcesView,+ PermissionGroup::ReconExceptionsView,+ PermissionGroup::ReconTransactionsView,+ PermissionGroup::ReconRulesView,],role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),role_name: "internal_view_only".to_string(),@@ -61,7 +67,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: false,is_updatable: false,is_internal: true,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: None,},);roles.insert(@@ -74,8 +80,10 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::AnalyticsView,PermissionGroup::UsersView,PermissionGroup::AccountView,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconReportsView,+ PermissionGroup::ReconSourcesView,+ PermissionGroup::ReconExceptionsView,+ PermissionGroup::ReconTransactionsView,+ PermissionGroup::ReconRulesView,PermissionGroup::InternalManage,],role_id: common_utils::consts::ROLE_ID_INTERNAL_DEMO.to_string(),@@ -86,7 +94,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: false,is_updatable: false,is_internal: true,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: None,},);@@ -106,10 +114,14 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::UsersManage,PermissionGroup::AccountView,PermissionGroup::AccountManage,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconOpsManage,- PermissionGroup::ReconReportsView,- PermissionGroup::ReconReportsManage,+ PermissionGroup::ReconSourcesView,+ PermissionGroup::ReconSourcesManage,+ PermissionGroup::ReconExceptionsView,+ PermissionGroup::ReconExceptionsManage,+ PermissionGroup::ReconTransactionsView,+ PermissionGroup::ReconTransactionsManage,+ PermissionGroup::ReconRulesView,+ PermissionGroup::ReconRulesManage,],role_id: common_utils::consts::ROLE_ID_TENANT_ADMIN.to_string(),role_name: "tenant_admin".to_string(),@@ -119,7 +131,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: false,is_updatable: false,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: None,},);@@ -139,12 +151,16 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::UsersManage,PermissionGroup::AccountView,PermissionGroup::AccountManage,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconOpsManage,- PermissionGroup::ReconReportsView,- PermissionGroup::ReconReportsManage,PermissionGroup::ThemeView,PermissionGroup::ThemeManage,+ PermissionGroup::ReconSourcesView,+ PermissionGroup::ReconSourcesManage,+ PermissionGroup::ReconExceptionsView,+ PermissionGroup::ReconExceptionsManage,+ PermissionGroup::ReconTransactionsView,+ PermissionGroup::ReconTransactionsManage,+ PermissionGroup::ReconRulesView,+ PermissionGroup::ReconRulesManage,],role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),role_name: "organization_admin".to_string(),@@ -154,7 +170,8 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ // Org level roles should not have any product type+ product_type_filter: None,},);@@ -174,10 +191,6 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::UsersManage,PermissionGroup::AccountView,PermissionGroup::AccountManage,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconOpsManage,- PermissionGroup::ReconReportsView,- PermissionGroup::ReconReportsManage,],role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),role_name: "merchant_admin".to_string(),@@ -187,7 +200,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -200,8 +213,6 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::AnalyticsView,PermissionGroup::UsersView,PermissionGroup::AccountView,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconReportsView,],role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),role_name: "merchant_view_only".to_string(),@@ -211,7 +222,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -232,7 +243,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -245,8 +256,6 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::UsersView,PermissionGroup::AccountView,PermissionGroup::AccountManage,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconReportsView,],role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),role_name: "merchant_developer".to_string(),@@ -256,7 +265,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -270,9 +279,6 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::AnalyticsView,PermissionGroup::UsersView,PermissionGroup::AccountView,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconOpsManage,- PermissionGroup::ReconReportsView,],role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),role_name: "merchant_operator".to_string(),@@ -282,7 +288,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -293,8 +299,6 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocPermissionGroup::AnalyticsView,PermissionGroup::UsersView,PermissionGroup::AccountView,- PermissionGroup::ReconOpsView,- PermissionGroup::ReconReportsView,],role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(),role_name: "customer_support".to_string(),@@ -304,7 +308,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);@@ -333,7 +337,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -355,7 +359,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -376,7 +380,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -398,7 +402,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -421,7 +425,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);roles.insert(@@ -441,7 +445,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Orchestration,+ product_type_filter: Some(MerchantProductType::Orchestration),},);// Recon Roles@@ -468,7 +472,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Recon,+ product_type_filter: Some(MerchantProductType::Recon),},);roles.insert(@@ -489,7 +493,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Recon,+ product_type_filter: Some(MerchantProductType::Recon),},);roles.insert(@@ -511,7 +515,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Recon,+ product_type_filter: Some(MerchantProductType::Recon),},);roles.insert(@@ -532,7 +536,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Recon,+ product_type_filter: Some(MerchantProductType::Recon),},);@@ -560,7 +564,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Recon,+ product_type_filter: Some(MerchantProductType::Recon),},);roles.insert(@@ -581,7 +585,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Recon,+ product_type_filter: Some(MerchantProductType::Recon),},);roles.insert(@@ -603,7 +607,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Recon,+ product_type_filter: Some(MerchantProductType::Recon),},);roles.insert(@@ -624,7 +628,7 @@ pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLocis_deletable: true,is_updatable: true,is_internal: false,- merchant_product_type: MerchantProductType::Recon,+ product_type_filter: Some(MerchantProductType::Recon),},);diff --git a/crates/router/src/types/domain/role.rs b/crates/router/src/types/domain/role.rsindex 0bdb095b3d..e1f4300a07 100644--- a/crates/router/src/types/domain/role.rs+++ b/crates/router/src/types/domain/role.rs@@ -1,6 +1,8 @@use common_enums::MerchantProductType;-#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]+#[derive(+ Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize, strum::EnumIter,+)]#[serde(rename_all = "snake_case")]pub enum RoleProductCategory {Dashboard,@@ -24,3 +26,32 @@ impl From<MerchantProductType> for RoleProductCategory {}}}++pub fn get_accessible_product_categories(+ product_type: MerchantProductType,+) -> Vec<RoleProductCategory> {+ match product_type {+ MerchantProductType::Orchestration => vec![+ RoleProductCategory::Orchestration,+ RoleProductCategory::Dashboard,+ ],+ MerchantProductType::Vault => {+ vec![RoleProductCategory::Vault, RoleProductCategory::Dashboard]+ }+ MerchantProductType::Recon => {+ vec![RoleProductCategory::Recon, RoleProductCategory::Dashboard]+ }+ MerchantProductType::Recovery => vec![+ RoleProductCategory::Recovery,+ RoleProductCategory::Dashboard,+ ],+ MerchantProductType::CostObservability => vec![+ RoleProductCategory::CostObservability,+ RoleProductCategory::Dashboard,+ ],+ MerchantProductType::DynamicRouting => vec![+ RoleProductCategory::DynamicRouting,+ RoleProductCategory::Dashboard,+ ],+ }+}diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rsindex 97c58117b4..b662e2f7d5 100644--- a/crates/router/src/utils/user_role.rs+++ b/crates/router/src/utils/user_role.rs@@ -20,7 +20,7 @@ use crate::{consts,core::errors::{UserErrors, UserResult},db::{- domain::role::RoleProductCategory,+ domain::role::get_accessible_product_categories,errors::StorageErrorExt,user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},},@@ -48,12 +48,9 @@ pub fn validate_role_groups(}if let Some(product_type) = merchant_product_type {- if !groups.iter().all(|group| {- let role_product_category = group.get_role_product_category();- match role_product_category {- RoleProductCategory::Dashboard => true,- _ => role_product_category == RoleProductCategory::from(product_type),- }+ let accessible_product_categories = get_accessible_product_categories(product_type);+ if groups.iter().any(|group| {+ !accessible_product_categories.contains(&group.get_role_product_category())}) {return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable("Permission groups of different product types found");diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 7df0454270..68fd1d2caf 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -255,14 +255,6 @@ pub enum Flow {RefundsAggregate,// Retrieve forex flow.RetrieveForexFlow,- /// Toggles recon service for a merchant.- ReconMerchantUpdate,- /// Recon token request flow.- ReconTokenRequest,- /// Initial request for recon service.- ReconServiceRequest,- /// Recon token verification flow- ReconVerifyToken,/// Routing create flow,RoutingCreateConfig,/// Routing link configdiff --git a/migrations/2026-04-16-000001_remove_legacy_recon_permission_groups/down.sql b/migrations/2026-04-16-000001_remove_legacy_recon_permission_groups/down.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/migrations/2026-04-16-000001_remove_legacy_recon_permission_groups/down.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/migrations/2026-04-16-000001_remove_legacy_recon_permission_groups/up.sql b/migrations/2026-04-16-000001_remove_legacy_recon_permission_groups/up.sqlnew file mode 100644index 0000000000..8eb85b89e0--- /dev/null+++ b/migrations/2026-04-16-000001_remove_legacy_recon_permission_groups/up.sql@@ -0,0 +1,15 @@+UPDATE roles+SET groups = array_remove(groups, 'recon_ops_view')+WHERE 'recon_ops_view' = ANY(groups);++UPDATE roles+SET groups = array_remove(groups, 'recon_ops_manage')+WHERE 'recon_ops_manage' = ANY(groups);++UPDATE roles+SET groups = array_remove(groups, 'recon_reports_view')+WHERE 'recon_reports_view' = ANY(groups);++UPDATE roles+SET groups = array_remove(groups, 'recon_reports_manage')+WHERE 'recon_reports_manage' = ANY(groups);