Skip to content

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

feat(vsaas): enable platform merchant API Key authentication for org-level operations (#8156)

Sandeep Kumar7a44626251c9
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index d9d48bf522..57624b229f 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -14865,7 +14865,8 @@
"primary_business_details",
"organization_id",
"is_recon_enabled",
- "recon_status"
+ "recon_status",
+ "merchant_account_type"
],
"properties": {
"merchant_id": {
@@ -15011,9 +15012,20 @@
}
],
"nullable": true
+ },
+ "merchant_account_type": {
+ "$ref": "#/components/schemas/MerchantAccountType"
}
}
},
+ "MerchantAccountType": {
+ "type": "string",
+ "enum": [
+ "standard",
+ "platform",
+ "connected"
+ ]
+ },
"MerchantAccountUpdate": {
"type": "object",
"required": [
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 1d026a6854..f4435b08fc 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -572,6 +572,10 @@ pub struct MerchantAccountResponse {
/// Product Type of this merchant account
#[schema(value_type = Option<MerchantProductType>, example = "Orchestration")]
pub product_type: Option<api_enums::MerchantProductType>,
+
+ /// Merchant Account Type of this merchant account
+ #[schema(value_type = MerchantAccountType, example = "standard")]
+ pub merchant_account_type: api_enums::MerchantAccountType,
}
#[cfg(feature = "v2")]
diff --git a/crates/common_enums/src/enums/accounts.rs b/crates/common_enums/src/enums/accounts.rs
index 7500dcac7c..46dae93466 100644
--- a/crates/common_enums/src/enums/accounts.rs
+++ b/crates/common_enums/src/enums/accounts.rs
@@ -38,6 +38,7 @@ pub enum MerchantProductType {
serde::Serialize,
strum::Display,
strum::EnumString,
+ ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[strum(serialize_all = "snake_case")]
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs
index 2cd1af9863..d272ff5269 100644
--- a/crates/hyperswitch_domain_models/src/merchant_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs
@@ -222,6 +222,14 @@ impl MerchantAccount {
pub fn get_org_id(&self) -> &common_utils::id_type::OrganizationId {
&self.organization_id
}
+
+ /// Check whether the merchant account is a platform account
+ pub fn is_platform_account(&self) -> bool {
+ matches!(
+ self.merchant_account_type,
+ common_enums::MerchantAccountType::Platform
+ )
+ }
}
#[cfg(feature = "v1")]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 4de9b85cd7..7a86b8a77f 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -461,6 +461,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::AmountInfo,
api_models::payments::ClickToPaySessionResponse,
api_models::enums::ProductType,
+ api_models::enums::MerchantAccountType,
api_models::payments::GooglePayWalletData,
api_models::payments::PayPalWalletData,
api_models::payments::PaypalRedirection,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index ca6b870f88..7aaebfc07c 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -446,6 +446,7 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element.
@@ -486,9 +487,16 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth {
- permission: Permission::OrganizationAnalyticsRead,
- },
+ auth::auth_type(
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: false,
+ organization_id: None,
+ },
+ &auth::JWTAuth {
+ permission: Permission::OrganizationAnalyticsRead,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -600,6 +608,7 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element.
@@ -640,9 +649,16 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth {
- permission: Permission::OrganizationAnalyticsRead,
- },
+ auth::auth_type(
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: false,
+ organization_id: None,
+ },
+ &auth::JWTAuth {
+ permission: Permission::OrganizationAnalyticsRead,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -754,6 +770,7 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetRefundMetricRequest` element.
@@ -794,9 +811,16 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth {
- permission: Permission::OrganizationAnalyticsRead,
- },
+ auth::auth_type(
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: false,
+ organization_id: None,
+ },
+ &auth::JWTAuth {
+ permission: Permission::OrganizationAnalyticsRead,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -1068,6 +1092,7 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
pub async fn get_org_payment_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
@@ -1088,9 +1113,16 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth {
- permission: Permission::OrganizationAnalyticsRead,
- },
+ auth::auth_type(
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: false,
+ organization_id: None,
+ },
+ &auth::JWTAuth {
+ permission: Permission::OrganizationAnalyticsRead,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -1132,6 +1164,7 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
pub async fn get_payment_intents_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
@@ -1152,9 +1185,16 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth {
- permission: Permission::MerchantAnalyticsRead,
- },
+ auth::auth_type(
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: false,
+ organization_id: None,
+ },
+ &auth::JWTAuth {
+ permission: Permission::MerchantAnalyticsRead,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -1190,6 +1230,7 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
pub async fn get_org_refund_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
@@ -1210,9 +1251,16 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth {
- permission: Permission::OrganizationAnalyticsRead,
- },
+ auth::auth_type(
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: false,
+ organization_id: None,
+ },
+ &auth::JWTAuth {
+ permission: Permission::OrganizationAnalyticsRead,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -2480,6 +2528,7 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
pub async fn get_org_dispute_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
@@ -2500,9 +2549,16 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth {
- permission: Permission::OrganizationAnalyticsRead,
- },
+ auth::auth_type(
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: false,
+ organization_id: None,
+ },
+ &auth::JWTAuth {
+ permission: Permission::OrganizationAnalyticsRead,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -2594,6 +2650,7 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element.
@@ -2624,9 +2681,16 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth {
- permission: Permission::OrganizationAnalyticsRead,
- },
+ auth::auth_type(
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: false,
+ organization_id: None,
+ },
+ &auth::JWTAuth {
+ permission: Permission::OrganizationAnalyticsRead,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -2663,6 +2727,7 @@ pub mod routes {
.await
}
+ #[cfg(feature = "v1")]
pub async fn get_org_sankey(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
@@ -2684,9 +2749,16 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth {
- permission: Permission::OrganizationAnalyticsRead,
- },
+ auth::auth_type(
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: false,
+ organization_id: None,
+ },
+ &auth::JWTAuth {
+ permission: Permission::OrganizationAnalyticsRead,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 15eea114ce..9e9329ac54 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -66,7 +66,10 @@ pub async fn organization_update(
json_payload.into_inner(),
|state, _, req, _| update_organization(state, org_id.clone(), req),
auth::auth_type(
- &auth::AdminApiAuth,
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: true,
+ organization_id: Some(organization_id.clone()),
+ },
&auth::JWTAuthOrganizationFromRoute {
organization_id,
required_permission: Permission::OrganizationAccountWrite,
@@ -128,7 +131,10 @@ pub async fn organization_retrieve(
payload,
|state, _, req, _| get_organization(state, req),
auth::auth_type(
- &auth::AdminApiAuth,
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: true,
+ organization_id: Some(organization_id.clone()),
+ },
&auth::JWTAuthOrganizationFromRoute {
organization_id,
required_permission: Permission::OrganizationAccountRead,
@@ -186,7 +192,10 @@ pub async fn merchant_account_create(
&req,
json_payload.into_inner(),
|state, auth, req, _| create_merchant_account(state, req, auth),
- &auth::AdminApiAuthWithApiKeyFallback,
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: true,
+ organization_id: None,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -249,7 +258,10 @@ pub async fn retrieve_merchant_account(
payload,
|state, _, req, _| get_merchant_account(state, req, None),
auth::auth_type(
- &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
+ &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
+ merchant_id_from_route: merchant_id.clone(),
+ is_admin_auth_allowed: true,
+ },
&auth::JWTAuthMerchantFromRoute {
merchant_id,
// This should ideally be MerchantAccountRead, but since FE is calling this API for
@@ -348,11 +360,12 @@ pub async fn merchant_account_list(
state,
&req,
query_params.into_inner(),
- |state, auth: Option<auth::AuthenticationDataWithOrg>, request, _| {
- list_merchant_account(state, request, auth)
- },
+ |state, auth, request, _| list_merchant_account(state, request, auth),
auth::auth_type(
- &auth::AdminApiAuthWithApiKeyFallback,
+ &auth::PlatformOrgAdminAuth {
+ is_admin_auth_allowed: true,
+ organization_id: None,
+ },
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountRead,
},
@@ -411,7 +424,10 @@ pub async fn update_merchant_account(
json_payload.into_inner(),
|state, _, req, _| merchant_account_update(state, &merchant_id, None, req),
auth::auth_type(
- &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
+ &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
+ merchant_id_from_route: merchant_id.clone(),
+ is_admin_auth_allowed: true,
+ },
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantAccountWrite,
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index 087e295dc8..3acb1c0706 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -29,7 +29,10 @@ pub async fn api_key_create(
api_keys::create_api_key(state, payload, auth_data.key_store).await
},
auth::auth_type(
- &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
+ &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
+ merchant_id_from_route: merchant_id.clone(),
+ is_admin_auth_allowed: true,
+ },
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantApiKeyWrite,
@@ -130,7 +133,10 @@ pub async fn api_key_retrieve(
(merchant_id.clone(), key_id.clone()),
|state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id),
auth::auth_type(
- &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
+ &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
+ merchant_id_from_route: merchant_id.clone(),
+ is_admin_auth_allowed: true,
+ },
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantApiKeyRead,
@@ -166,7 +172,10 @@ pub async fn api_key_update(
payload,
|state, _, payload, _| api_keys::update_api_key(state, payload),
auth::auth_type(
- &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
+ &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
+ merchant_id_from_route: merchant_id.clone(),
+ is_admin_auth_allowed: true,
+ },
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantApiKeyWrite,
@@ -236,7 +245,10 @@ pub async fn api_key_revoke(
(&merchant_id, &key_id),
|state, _, (merchant_id, key_id), _| api_keys::revoke_api_key(state, merchant_id, key_id),
auth::auth_type(
- &auth::AdminApiAuth,
+ &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
+ merchant_id_from_route: merchant_id.clone(),
+ is_admin_auth_allowed: true,
+ },
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantApiKeyWrite,
@@ -303,7 +315,10 @@ pub async fn api_key_list(
api_keys::list_api_keys(state, merchant_id, limit, offset).await
},
auth::auth_type(
- &auth::AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(merchant_id.clone()),
+ &auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
+ merchant_id_from_route: merchant_id.clone(),
+ is_admin_auth_allowed: true,
+ },
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantApiKeyRead,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 15e6c6e95c..5fd65a22be 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -696,6 +696,342 @@ where
}
}
+#[derive(Debug, Default)]
+pub struct PlatformOrgAdminAuth {
+ pub is_admin_auth_allowed: bool,
+ pub organization_id: Option<id_type::OrganizationId>,
+}
+
+#[cfg(feature = "v1")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for PlatformOrgAdminAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> {
+ // Step 1: Admin API Key and API Key Fallback (if allowed)
+ if self.is_admin_auth_allowed {
+ let admin_auth = AdminApiAuthWithApiKeyFallback;
+ match admin_auth
+ .authenticate_and_fetch(request_headers, state)
+ .await
+ {
+ Ok((auth, auth_type)) => {
+ return Ok((auth, auth_type));
+ }
+ Err(e) => {
+ logger::warn!("Admin API Auth failed: {:?}", e);
+ }
+ }
+ }
+
+ // Step 2: Try Platform Auth
+ let api_key = get_api_key(request_headers)
+ .change_context(errors::ApiErrorResponse::Unauthorized)?
+ .trim();
+ if api_key.is_empty() {
+ return Err(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("API key is empty");
+ }
+
+ let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key);
+ let hash_key = state.conf().api_keys.get_inner().get_hash_key()?;
+ let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek());
+
+ let stored_api_key = state
+ .store()
+ .find_api_key_by_hash_optional(hashed_api_key.into())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to retrieve API key")?
+ .ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("Merchant not authenticated via API key")?;
+
+ if stored_api_key
+ .expires_at
+ .map(|expires_at| expires_at < date_time::now())
+ .unwrap_or(false)
+ {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("API key has expired");
+ }
+
+ let key_manager_state = &(&state.session_state()).into();
+
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &stored_api_key.merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")?;
+
+ let merchant_account = state
+ .store()
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &stored_api_key.merchant_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("Merchant account not found")?;
+
+ if !(state.conf().platform.enabled && merchant_account.is_platform_account()) {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("Platform authentication check failed"));
+ }
+
+ if let Some(ref organization_id) = self.organization_id {
+ if organization_id != merchant_account.get_org_id() {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("Organization ID does not match");
+ }
+ }
+
+ Ok((
+ Some(AuthenticationDataWithOrg {
+ organization_id: merchant_account.get_org_id().clone(),
+ }),
+ AuthenticationType::ApiKey {
+ merchant_id: merchant_account.get_id().clone(),
+ key_id: stored_api_key.key_id,
+ },
+ ))
+ }
+}
+
+#[cfg(feature = "v1")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationData, A> for PlatformOrgAdminAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ let api_key = get_api_key(request_headers)
+ .change_context(errors::ApiErrorResponse::Unauthorized)?
+ .trim();
+ if api_key.is_empty() {
+ return Err(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("API key is empty");
+ }
+
+ let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key);
+ let hash_key = state.conf().api_keys.get_inner().get_hash_key()?;
+ let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek());
+
+ let stored_api_key = state
+ .store()
+ .find_api_key_by_hash_optional(hashed_api_key.into())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to retrieve API key")?
+ .ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("Merchant not authenticated via API key")?;
+
+ if stored_api_key
+ .expires_at
+ .map(|expires_at| expires_at < date_time::now())
+ .unwrap_or(false)
+ {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("API key has expired");
+ }
+
+ let key_manager_state = &(&state.session_state()).into();
+
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &stored_api_key.merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("Failed to fetch merchant key store for the merchant id")?;
+
+ let merchant_account = state
+ .store()
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &stored_api_key.merchant_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("Merchant account not found")?;
+
+ if !(state.conf().platform.enabled && merchant_account.is_platform_account()) {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("Platform authentication check failed"));
+ }
+
+ if let Some(ref organization_id) = self.organization_id {
+ if organization_id != merchant_account.get_org_id() {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("Organization ID does not match");
+ }
+ }
+
+ let auth = AuthenticationData {
+ merchant_account: merchant_account.clone(),
+ platform_merchant_account: Some(merchant_account.clone()),
+ key_store,
+ profile_id: None,
+ };
+
+ Ok((
+ auth.clone(),
+ AuthenticationType::ApiKey {
+ merchant_id: auth.merchant_account.get_id().clone(),
+ key_id: stored_api_key.key_id,
+ },
+ ))
+ }
+}
+
+#[derive(Debug)]
+pub struct PlatformOrgAdminAuthWithMerchantIdFromRoute {
+ pub merchant_id_from_route: id_type::MerchantId,
+ pub is_admin_auth_allowed: bool,
+}
+
+#[cfg(feature = "v1")]
+impl PlatformOrgAdminAuthWithMerchantIdFromRoute {
+ async fn fetch_key_store_and_account<A: SessionStateInfo + Sync>(
+ merchant_id: &id_type::MerchantId,
+ state: &A,
+ ) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> {
+ let key_manager_state = &(&state.session_state()).into();
+
+ let key_store = state
+ .store()
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ merchant_id,
+ &state.store().get_master_key().to_vec().into(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
+
+ let merchant = state
+ .store()
+ .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
+
+ Ok((key_store, merchant))
+ }
+}
+
+#[cfg(feature = "v1")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationData, A> for PlatformOrgAdminAuthWithMerchantIdFromRoute
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ let route_merchant_id = self.merchant_id_from_route.clone();
+
+ // Step 1: Admin API Key and API Key Fallback (if allowed)
+ if self.is_admin_auth_allowed {
+ let admin_auth =
+ AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(route_merchant_id.clone());
+
+ match admin_auth
+ .authenticate_and_fetch(request_headers, state)
+ .await
+ {
+ Ok((auth_data, auth_type)) => return Ok((auth_data, auth_type)),
+ Err(e) => {
+ logger::warn!("Admin API Auth failed: {:?}", e);
+ }
+ }
+ }
+
+ // Step 2: Platform authentication
+ let api_key = get_api_key(request_headers)
+ .change_context(errors::ApiErrorResponse::Unauthorized)?
+ .trim();
+ if api_key.is_empty() {
+ return Err(errors::ApiErrorResponse::Unauthorized)
+ .attach_printable("API key is empty");
+ }
+
+ let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key);
+ let hash_key = {
+ let config = state.conf();
+ config.api_keys.get_inner().get_hash_key()?
+ };
+ let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek());
+
+ let stored_api_key = state
+ .store()
+ .find_api_key_by_hash_optional(hashed_api_key.into())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to retrieve API key")?
+ .ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("Merchant not authenticated via API key")?;
+
+ if stored_api_key
+ .expires_at
+ .map(|expires_at| expires_at < date_time::now())
+ .unwrap_or(false)
+ {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("API key has expired");
+ }
+
+ let (_, platform_merchant) =
+ Self::fetch_key_store_and_account(&stored_api_key.merchant_id, state).await?;
+
+ if !(state.conf().platform.enabled && platform_merchant.is_platform_account()) {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("Platform authentication check failed");
+ }
+
+ let (route_key_store, route_merchant) =
+ Self::fetch_key_store_and_account(&route_merchant_id, state).await?;
+
+ if platform_merchant.get_org_id() != route_merchant.get_org_id() {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("Route merchant not under same org as platform merchant");
+ }
+
+ let auth = AuthenticationData {
+ merchant_account: route_merchant,
+ platform_merchant_account: Some(platform_merchant.clone()),
+ key_store: route_key_store,
+ profile_id: None,
+ };
+
+ Ok((
+ auth.clone(),
+ AuthenticationType::ApiKey {
+ merchant_id: platform_merchant.get_id().clone(),
+ key_id: stored_api_key.key_id,
+ },
+ ))
+ }
+}
+
#[cfg(not(feature = "partial-auth"))]
#[async_trait]
impl<A, I> AuthenticateAndFetch<AuthenticationData, A> for HeaderAuth<I>
@@ -2581,6 +2917,46 @@ pub struct JWTAuthOrganizationFromRoute {
pub required_permission: Permission,
}
+#[cfg(feature = "v1")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for JWTAuthOrganizationFromRoute
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(Option<AuthenticationDataWithOrg>, 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.required_permission, &role_info)?;
+
+ // Check if token has access to Organization that has been requested in the route
+ if payload.org_id != self.organization_id {
+ return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
+ }
+ Ok((
+ Some(AuthenticationDataWithOrg {
+ organization_id: payload.org_id.clone(),
+ }),
+ AuthenticationType::OrganizationJwt {
+ org_id: payload.org_id,
+ user_id: payload.user_id,
+ },
+ ))
+ }
+}
+
+#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for JWTAuthOrganizationFromRoute
where
@@ -4146,8 +4522,7 @@ fn get_and_validate_connected_merchant_id(
headers::X_CONNECTED_MERCHANT_ID,
)?
.map(|merchant_id| {
- merchant_account
- .is_platform_account
+ (merchant_account.is_platform_account())
.then_some(merchant_id)
.ok_or(errors::ApiErrorResponse::InvalidPlatformOperation)
})
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 50bd54756d..f0f3e1f7af 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -92,6 +92,7 @@ impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
recon_status: item.recon_status,
pm_collect_link_config,
product_type: item.product_type,
+ merchant_account_type: item.merchant_account_type,
})
}
}