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
fix(authentication): add Organization context validation in `Merchant Create` and `Merchant List` APIs (#8103)
Sandeep Kumar7fee571061ac
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex a97ff2cb68..2ab4e68715 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -190,6 +190,7 @@ pub async fn get_organization(pub async fn create_merchant_account(state: SessionState,req: api::MerchantAccountCreate,+ org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,) -> RouterResponse<api::MerchantAccountResponse> {#[cfg(feature = "keymanager_create")]use common_utils::{keymanager, types::keymanager::EncryptionTransferRequest};@@ -242,7 +243,12 @@ pub async fn create_merchant_account(};let domain_merchant_account = req- .create_domain_model_from_request(&state, key_store.clone(), &merchant_id)+ .create_domain_model_from_request(+ &state,+ key_store.clone(),+ &merchant_id,+ org_data_from_auth,+ ).await?;let key_manager_state = &(&state).into();db.insert_merchant_key_store(@@ -301,6 +307,7 @@ trait MerchantAccountCreateBridge {state: &SessionState,key: domain::MerchantKeyStore,identifier: &id_type::MerchantId,+ org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,) -> RouterResult<domain::MerchantAccount>;}@@ -312,6 +319,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {state: &SessionState,key_store: domain::MerchantKeyStore,identifier: &id_type::MerchantId,+ org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,) -> RouterResult<domain::MerchantAccount> {let db = &*state.accounts_store;let publishable_key = create_merchant_publishable_key();@@ -361,7 +369,22 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {).await?;- let organization = CreateOrValidateOrganization::new(self.organization_id)+ let org_id = match (&self.organization_id, &org_data_from_auth) {+ (Some(req_org_id), Some(auth)) => {+ if req_org_id != &auth.organization_id {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: "Mismatched organization_id in request and authenticated context"+ .to_string(),+ }+ .into());+ }+ Some(req_org_id.clone())+ }+ (None, Some(auth)) => Some(auth.organization_id.clone()),+ (req_org_id, _) => req_org_id.clone(),+ };++ let organization = CreateOrValidateOrganization::new(org_id).create_or_validate(db).await?;@@ -667,6 +690,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {state: &SessionState,key_store: domain::MerchantKeyStore,identifier: &id_type::MerchantId,+ _org_data: Option<authentication::AuthenticationDataWithOrg>,) -> RouterResult<domain::MerchantAccount> {let publishable_key = create_merchant_publishable_key();let db = &*state.accounts_store;@@ -787,7 +811,16 @@ pub async fn list_merchant_account(pub async fn list_merchant_account(state: SessionState,req: api_models::admin::MerchantAccountListRequest,+ org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,) -> RouterResponse<Vec<api::MerchantAccountResponse>> {+ if let Some(auth) = org_data_from_auth {+ if auth.organization_id != req.organization_id {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: "Organization ID in request and authentication do not match".to_string(),+ }+ .into());+ }+ }let merchant_accounts = state.store.list_merchant_accounts_by_organization_id(&(&state).into(), &req.organization_id)diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rsindex 903ac7c533..6554ec1b01 100644--- a/crates/router/src/core/user.rs+++ b/crates/router/src/core/user.rs@@ -1584,13 +1584,22 @@ pub async fn create_org_merchant_for_user(.await.change_context(UserErrors::InternalServerError)?;let default_product_type = consts::user::DEFAULT_PRODUCT_TYPE;- let merchant_account_create_request =- utils::user::create_merchant_account_request_for_org(req, org, default_product_type)?;+ let merchant_account_create_request = utils::user::create_merchant_account_request_for_org(+ req,+ org.clone(),+ default_product_type,+ )?;- admin::create_merchant_account(state.clone(), merchant_account_create_request)- .await- .change_context(UserErrors::InternalServerError)- .attach_printable("Error while creating a merchant")?;+ admin::create_merchant_account(+ state.clone(),+ merchant_account_create_request,+ Some(auth::AuthenticationDataWithOrg {+ organization_id: org.get_organization_id(),+ }),+ )+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Error while creating a merchant")?;Ok(ApplicationResponse::StatusOk)}diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rsindex 945ce2cee4..15eea114ce 100644--- a/crates/router/src/routes/admin.rs+++ b/crates/router/src/routes/admin.rs@@ -185,7 +185,7 @@ pub async fn merchant_account_create(state,&req,json_payload.into_inner(),- |state, _, req, _| create_merchant_account(state, req),+ |state, auth, req, _| create_merchant_account(state, req, auth),&auth::AdminApiAuthWithApiKeyFallback,api_locking::LockAction::NotApplicable,))@@ -223,7 +223,7 @@ pub async fn merchant_account_create(state,&req,new_request_payload_with_org_id,- |state, _, req, _| create_merchant_account(state, req),+ |state, _, req, _| create_merchant_account(state, req, None),&auth::V2AdminApiAuth,api_locking::LockAction::NotApplicable,))@@ -348,7 +348,9 @@ pub async fn merchant_account_list(state,&req,query_params.into_inner(),- |state, _, request, _| list_merchant_account(state, request),+ |state, auth: Option<auth::AuthenticationDataWithOrg>, request, _| {+ list_merchant_account(state, request, auth)+ },auth::auth_type(&auth::AdminApiAuthWithApiKeyFallback,&auth::JWTAuthMerchantFromHeader {diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 6a5683d4e4..15e6c6e95c 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -98,6 +98,11 @@ pub struct AuthenticationDataWithUser {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,@@ -1330,7 +1335,8 @@ pub struct AdminApiAuthWithApiKeyFallback;#[cfg(feature = "v1")]#[async_trait]-impl<A> AuthenticateAndFetch<(), A> for AdminApiAuthWithApiKeyFallback+impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A>+ for AdminApiAuthWithApiKeyFallbackwhereA: SessionStateInfo + Sync,{@@ -1338,7 +1344,7 @@ where&self,request_headers: &HeaderMap,state: &A,- ) -> RouterResult<((), AuthenticationType)> {+ ) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> {let request_api_key =get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;@@ -1347,7 +1353,7 @@ wherelet admin_api_key = &conf.secrets.get_inner().admin_api_key;if request_api_key == admin_api_key.peek() {- return Ok(((), AuthenticationType::AdminApiKey));+ return Ok((None, AuthenticationType::AdminApiKey));}let Some(fallback_merchant_ids) = conf.fallback_merchant_ids_api_key_auth.as_ref() else {return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(@@ -1377,12 +1383,37 @@ where.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 = 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)?;+if fallback_merchant_ids.merchant_ids.contains(&stored_api_key.merchant_id){return Ok((- (),+ Some(AuthenticationDataWithOrg {+ organization_id: merchant.organization_id,+ }),AuthenticationType::ApiKey {merchant_id: stored_api_key.merchant_id,key_id: stored_api_key.key_id,@@ -2705,6 +2736,50 @@ where}}+#[cfg(feature = "v1")]+#[async_trait]+impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for JWTAuthMerchantFromHeader+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)?;++ let merchant_id_from_header = HeaderMapStruct::new(request_headers)+ .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;++ // Check if token has access to MerchantId that has been requested through headers+ if payload.merchant_id != merchant_id_from_header {+ return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));+ }++ let auth = Some(AuthenticationDataWithOrg {+ organization_id: payload.org_id,+ });++ Ok((+ auth,+ AuthenticationType::MerchantJwt {+ merchant_id: payload.merchant_id,+ user_id: Some(payload.user_id),+ },+ ))+ }+}+#[cfg(feature = "v2")]#[async_trait]impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromHeaderdiff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rsindex 90af10ba53..181d56d1cb 100644--- a/crates/router/src/types/domain/user.rs+++ b/crates/router/src/types/domain/user.rs@@ -36,7 +36,10 @@ use crate::{},db::GlobalStorageInterface,routes::SessionState,- services::{self, authentication::UserFromToken},+ services::{+ self,+ authentication::{AuthenticationDataWithOrg, UserFromToken},+ },types::{domain, transformers::ForeignFrom},utils::{self, user::password},};@@ -518,13 +521,21 @@ impl NewUserMerchant {let merchant_account_create_request = self.create_merchant_account_request().attach_printable("unable to construct merchant account create request")?;-- let ApplicationResponse::Json(merchant_account_response) = Box::pin(- admin::create_merchant_account(state.clone(), merchant_account_create_request),- )- .await- .change_context(UserErrors::InternalServerError)- .attach_printable("Error while creating a merchant")?+ let org_id = merchant_account_create_request+ .clone()+ .organization_id+ .ok_or(UserErrors::InternalServerError)?;+ let ApplicationResponse::Json(merchant_account_response) =+ Box::pin(admin::create_merchant_account(+ state.clone(),+ merchant_account_create_request,+ Some(AuthenticationDataWithOrg {+ organization_id: org_id,+ }),+ ))+ .await+ .change_context(UserErrors::InternalServerError)+ .attach_printable("Error while creating a merchant")?else {return Err(UserErrors::InternalServerError.into());};@@ -566,7 +577,7 @@ impl NewUserMerchant {.attach_printable("unable to construct merchant account create request")?;let ApplicationResponse::Json(merchant_account_response) = Box::pin(- admin::create_merchant_account(state.clone(), merchant_account_create_request),+ admin::create_merchant_account(state.clone(), merchant_account_create_request, None),).await.change_context(UserErrors::InternalServerError)