Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

fix(analytics): Prevent cross owner resource access (#15092)

Anurag Thakurf8cd2a9e77ef
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs
index f5cf67dc7d..a0226bf32f 100644
--- a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs
@@ -55,6 +55,8 @@ where
)
.switch()?;
+ auth.set_filter_clause(&mut inner_query_builder).switch()?;
+
time_range
.set_filter_clause(&mut inner_query_builder)
.attach_printable("Error filtering time range for inner query")
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs
index 95be97e7af..f32ac9d1fd 100644
--- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs
@@ -55,6 +55,8 @@ where
)
.switch()?;
+ auth.set_filter_clause(&mut inner_query_builder).switch()?;
+
time_range
.set_filter_clause(&mut inner_query_builder)
.attach_printable("Error filtering time range for inner query")
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs
index 6e7f5ecb18..263110b6da 100644
--- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs
@@ -54,6 +54,8 @@ where
)
.switch()?;
+ auth.set_filter_clause(&mut inner_query_builder).switch()?;
+
time_range
.set_filter_clause(&mut inner_query_builder)
.attach_printable("Error filtering time range for inner query")
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 8223f53cc8..6e6b344caa 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -40,7 +40,9 @@ pub mod routes {
use router_env::logger;
use crate::{
- analytics_validator::{request_validator, validate_report_request},
+ analytics_validator::{
+ request_validator, validate_analytics_scope, validate_report_request,
+ },
consts::opensearch::SEARCH_INDEXES,
core::{api_locking, errors::user::UserErrors, verification::utils},
db::user_role::ListUserRolesByUserIdPayload,
@@ -587,6 +589,14 @@ pub mod routes {
payload,
|state, auth: AuthenticationData, req, _| async move {
let auth_info = auth.platform.to_merchant_level_auth_info();
+ validate_analytics_scope(
+ &auth_info,
+ &req.filters.merchant_id,
+ &req.filters.profile_id,
+ )
+ .attach_printable(
+ "Failed to validate analytics scope for merchant payment metrics",
+ )?;
let validator_response = request_validator(
AnalyticsRequest {
payment_attempt: Some(req.clone()),
@@ -696,6 +706,14 @@ pub mod routes {
.clone();
let auth_info: AuthInfo = auth.platform.to_profile_level_auth_info(profile_id);
+ validate_analytics_scope(
+ &auth_info,
+ &req.filters.merchant_id,
+ &req.filters.profile_id,
+ )
+ .attach_printable(
+ "Failed to validate analytics scope for profile payment metrics",
+ )?;
let validator_response = request_validator(
AnalyticsRequest {
payment_attempt: Some(req.clone()),
@@ -743,6 +761,14 @@ pub mod routes {
|state, auth: AuthenticationData, req, _| async move {
let auth_info = auth.platform.to_merchant_level_auth_info();
+ validate_analytics_scope(
+ &auth_info,
+ &req.filters.merchant_id,
+ &req.filters.profile_id,
+ )
+ .attach_printable(
+ "Failed to validate analytics scope for merchant payment intent metrics",
+ )?;
let validator_response = request_validator(
AnalyticsRequest {
payment_intent: Some(req.clone()),
@@ -2396,7 +2422,17 @@ pub mod routes {
.get_id()
.clone();
- let auth_info = vec![auth.platform.to_profile_level_auth_info(profile_id)];
+ let auth_info = auth.platform.to_profile_level_auth_info(profile_id);
+
+ validate_analytics_scope(
+ &auth_info,
+ &[],
+ constraints.profile_id.as_slice(),
+ )
+ .change_context(OpenSearchError::AccessForbiddenError)
+ .attach_printable(
+ "Failed to validate analytics scope for profile payment list",
+ )?;
let filters: SearchFilters = (&constraints).into();
@@ -2418,7 +2454,7 @@ pub mod routes {
.as_ref()
.ok_or_else(|| error_stack::report!(OpenSearchError::NotEnabled))?,
search_req,
- auth_info,
+ vec![auth_info],
)
.await
.map(|response| {
diff --git a/crates/router/src/analytics_validator.rs b/crates/router/src/analytics_validator.rs
index ea88f40d7e..1bc85edeb7 100644
--- a/crates/router/src/analytics_validator.rs
+++ b/crates/router/src/analytics_validator.rs
@@ -1,11 +1,39 @@
-use analytics::errors::AnalyticsError;
+use analytics::{enums::AuthInfo, errors::AnalyticsError};
use api_models::analytics::{AnalyticsRequest, ReportRequest};
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, id_type};
use currency_conversion::types::ExchangeRates;
use router_env::logger;
use crate::core::currency::get_forex_exchange_rates;
+/// Reject scope mismatches detectable from authenticated IDs
+/// The analytics query's authorization predicates enforce the remaining ownership boundaries.
+pub fn validate_analytics_scope(
+ auth: &AuthInfo,
+ merchant_ids: &[id_type::MerchantId],
+ profile_ids: &[id_type::ProfileId],
+) -> CustomResult<(), AnalyticsError> {
+ let allowed = match auth {
+ AuthInfo::OrgLevel { .. } => true,
+ AuthInfo::MerchantLevel {
+ merchant_ids: allowed_merchants,
+ ..
+ } => merchant_ids.iter().all(|id| allowed_merchants.contains(id)),
+ AuthInfo::ProfileLevel {
+ merchant_id,
+ profile_ids: allowed_profiles,
+ ..
+ } => {
+ merchant_ids.iter().all(|id| id == merchant_id)
+ && profile_ids.iter().all(|id| allowed_profiles.contains(id))
+ }
+ };
+ if !allowed {
+ return Err(AnalyticsError::AccessForbiddenError.into());
+ }
+ Ok(())
+}
+
pub async fn request_validator(
req_type: AnalyticsRequest,
state: &crate::routes::SessionState,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 505d37888a..127173ca3f 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -5117,6 +5117,11 @@ where
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
+ fp_utils::when(merchant.get_org_id() != &payload.org_id, || {
+ Err(report!(errors::ApiErrorResponse::InvalidJwtToken))
+ .attach_printable("JWT merchant does not belong to JWT organization")
+ })?;
+
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
diff --git a/crates/storage_impl/src/business_profile.rs b/crates/storage_impl/src/business_profile.rs
index d59e4a5b12..a392d5fa64 100644
--- a/crates/storage_impl/src/business_profile.rs
+++ b/crates/storage_impl/src/business_profile.rs
@@ -282,30 +282,24 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
.attach_printable("Missing KeyManagerState")?;
#[cfg(not(feature = "accounts_cache"))]
- {
- fetch_func()
- .await?
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(StorageError::DecryptionError)
- }
+ let profile = fetch_func().await?;
#[cfg(feature = "accounts_cache")]
- {
- let profile = Box::pin(cache::get_or_populate_in_memory_redis(
- self,
- &profile_cache_key(profile_id),
- fetch_func(),
- CacheId::Accounts,
- ))
- .await?;
-
- validate_cached_profile_ownership(&profile.merchant_id, merchant_id, profile_id)?;
+ let profile = Box::pin(cache::get_or_populate_in_memory_redis(
+ self,
+ &profile_cache_key(profile_id),
+ fetch_func(),
+ CacheId::Accounts,
+ ))
+ .await?;
+ // The cache is also populated by the lookup using only profile_id. Its key
+ // does not establish merchant ownership, so validate before decrypting it.
+ if profile.merchant_id != *merchant_id {
+ Err(report!(StorageError::ValueNotFound(
+ "Business profile not found for merchant".to_string(),
+ )))
+ } else {
profile
.convert(
state,