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(auth): add new authentication to communicate between microservices (#9547)
Jaganb8900d008ae4
diff --git a/config/config.example.toml b/config/config.example.tomlindex ff185baa41..57c3a6a378 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1271,3 +1271,8 @@ encryption_key = "" # Key to encrypt and decrypt chatproxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response[list_dispute_supported_connectors]connector_list = "worldpayvantiv"++# Authentication to communicate between internal services using common_api_key, merchant id and profile id+[internal_merchant_id_profile_id_auth]+enabled = false # Enable or disable internal api key, merchant id and profile id based authentication+internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication\ No newline at end of filediff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex b798d912dc..d48ab2d148 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -24,6 +24,10 @@ queue_strategy = "Fifo" # Add the queue strategy used by the database bb8 clie[api_keys]hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" # API key hashing key.+[internal_merchant_id_profile_id_auth]+enabled = false+internal_api_key = "test_internal_api_key"+[applepay_decrypt_keys]apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" # Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificateapple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" # Private key generated by Elliptic-curve prime256v1 curve. You can use `openssl ecparam -out private.key -name prime256v1 -genkey` to generate the private keydiff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.tomlindex ca41684c0b..1f12befea6 100644--- a/config/deployments/integration_test.toml+++ b/config/deployments/integration_test.toml@@ -909,3 +909,8 @@ connector_list = "worldpayvantiv"[grpc_client.unified_connector_service]ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS onlyucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call++# Authentication to communicate between internal services using common_api_key, merchant id and profile id+[internal_merchant_id_profile_id_auth]+enabled = false # Enable or disable internal api key, merchant id and profile id based authentication+internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication\ No newline at end of filediff --git a/config/deployments/production.toml b/config/deployments/production.tomlindex 8c4fbf4f6a..2393a9d9e0 100644--- a/config/deployments/production.toml+++ b/config/deployments/production.toml@@ -916,3 +916,8 @@ click_to_pay = {connector_list = "adyen, cybersource, trustpay"}[grpc_client.unified_connector_service]ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS onlyucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call++# Authentication to communicate between internal services using common_api_key, merchant id and profile id+[internal_merchant_id_profile_id_auth]+enabled = false # Enable or disable internal api key, merchant id and profile id based authentication+internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authenticationdiff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.tomlindex e734779c64..a3baebc0ae 100644--- a/config/deployments/sandbox.toml+++ b/config/deployments/sandbox.toml@@ -924,3 +924,8 @@ connector_list = "worldpayvantiv"[grpc_client.unified_connector_service]ucs_only_connectors = "paytm, phonepe" # Comma-separated list of connectors that use UCS onlyucs_psync_disabled_connectors = "cashtocode" # Comma-separated list of connectors to disable UCS PSync call++# Authentication to communicate between internal services using common_api_key, merchant id and profile id+[internal_merchant_id_profile_id_auth]+enabled = false # Enable or disable internal api key, merchant id and profile id based authentication+internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication\ No newline at end of filediff --git a/config/development.toml b/config/development.tomlindex afab067718..6b53c46e05 100644--- a/config/development.toml+++ b/config/development.toml@@ -1385,3 +1385,7 @@ encryption_key = ""proxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response[list_dispute_supported_connectors]connector_list = "worldpayvantiv"++[internal_merchant_id_profile_id_auth]+enabled = false+internal_api_key = "test_internal_api_key"\ No newline at end of filediff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 4ebe2db76b..93bef2e3ef 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -1280,3 +1280,8 @@ version = "HOSTNAME" # value of HOSTNAME from deployment which tells itsproxy_connector_http_status_code = false # If enabled, the http status code of the connector will be proxied in the response[list_dispute_supported_connectors]connector_list = "worldpayvantiv"++# Authentication to communicate between internal services using common_api_key, merchant id and profile id+[internal_merchant_id_profile_id_auth]+enabled = false # Enable or disable internal api key, merchant id and profile id based authentication+internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication\ No newline at end of filediff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex 53ce32b033..67b6854922 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -576,6 +576,7 @@ pub(crate) async fn fetch_raw_secrets(debit_routing_config: conf.debit_routing_config,clone_connector_allowlist: conf.clone_connector_allowlist,merchant_id_auth: conf.merchant_id_auth,+ internal_merchant_id_profile_id_auth: conf.internal_merchant_id_profile_id_auth,infra_values: conf.infra_values,enhancement: conf.enhancement,proxy_status_mapping: conf.proxy_status_mapping,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 223b5ae4cb..d504cce40f 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -163,6 +163,7 @@ pub struct Settings<S: SecretState> {pub revenue_recovery: revenue_recovery::RevenueRecoverySettings,pub clone_connector_allowlist: Option<CloneConnectorAllowlistConfig>,pub merchant_id_auth: MerchantIdAuthSettings,+ pub internal_merchant_id_profile_id_auth: InternalMerchantIdProfileIdAuthSettings,#[serde(default)]pub infra_values: Option<HashMap<String, String>>,#[serde(default)]@@ -858,6 +859,13 @@ pub struct MerchantIdAuthSettings {pub merchant_id_auth_enabled: bool,}+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(default)]+pub struct InternalMerchantIdProfileIdAuthSettings {+ pub enabled: bool,+ pub internal_api_key: Secret<String>,+}+#[derive(Debug, Clone, Default, Deserialize)]#[serde(default)]pub struct ProxyStatusMapping {diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rsindex c746410aa0..679ef8aff3 100644--- a/crates/router/src/lib.rs+++ b/crates/router/src/lib.rs@@ -67,6 +67,7 @@ pub mod headers {pub const X_API_VERSION: &str = "X-ApiVersion";pub const X_FORWARDED_FOR: &str = "X-Forwarded-For";pub const X_MERCHANT_ID: &str = "X-Merchant-Id";+ pub const X_INTERNAL_API_KEY: &str = "X-Internal-Api-Key";pub const X_ORGANIZATION_ID: &str = "X-Organization-Id";pub const X_LOGIN: &str = "X-Login";pub const X_TRANS_KEY: &str = "X-Trans-Key";diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 696f47a4c0..acbb7b6072 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1174,7 +1174,7 @@ pub struct Subscription;#[cfg(all(feature = "oltp", feature = "v1"))]impl Subscription {pub fn server(state: AppState) -> Scope {- let route = web::scope("/subscription").app_data(web::Data::new(state.clone()));+ let route = web::scope("/subscriptions").app_data(web::Data::new(state.clone()));route.service(web::resource("/create").route(diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex c1970b64c2..3bf2f47283 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -78,6 +78,25 @@ pub async fn payments_create(let locking_action = payload.get_locking_input(flow.clone());+ let auth_type = match env::which() {+ env::Env::Production => {+ &auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth {+ is_connected_allowed: false,+ is_platform_allowed: true,+ }))+ }+ _ => auth::auth_type(+ &auth::InternalMerchantIdProfileIdAuth(auth::HeaderAuth(auth::ApiKeyAuth {+ is_connected_allowed: false,+ is_platform_allowed: true,+ })),+ &auth::InternalMerchantIdProfileIdAuth(auth::JWTAuth {+ permission: Permission::ProfilePaymentWrite,+ }),+ req.headers(),+ ),+ };+Box::pin(api::server_wrap(flow,state,@@ -98,22 +117,7 @@ pub async fn payments_create(api::AuthFlow::Client,)},- match env::which() {- env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth {- is_connected_allowed: false,- is_platform_allowed: true,- }),- _ => auth::auth_type(- &auth::HeaderAuth(auth::ApiKeyAuth {- is_connected_allowed: false,- is_platform_allowed: true,- }),- &auth::JWTAuth {- permission: Permission::ProfilePaymentWrite,- },- req.headers(),- ),- },+ auth_type,locking_action,)).await@@ -569,11 +573,15 @@ pub async fn payments_retrieve(is_platform_allowed: true,};- let (auth_type, auth_flow) =- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {- Ok(auth) => auth,- Err(err) => return api::log_and_return_error_response(report!(err)),- };+ let (auth_type, auth_flow) = match auth::check_internal_api_key_auth(+ req.headers(),+ &payload,+ api_auth,+ state.conf.internal_merchant_id_profile_id_auth.clone(),+ ) {+ Ok(auth) => auth,+ Err(err) => return api::log_and_return_error_response(report!(err)),+ };let locking_action = payload.get_locking_input(flow.clone());diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 851c2cf21b..13d224a1cd 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -38,6 +38,7 @@ use crate::core::errors::UserResult;#[cfg(all(feature = "partial-auth", feature = "v1"))]use crate::core::metrics;use crate::{+ configs::settings,core::{api_keys,errors::{self, utils::StorageErrorExt, RouterResult},@@ -155,6 +156,10 @@ pub enum AuthenticationType {WebhookAuth {merchant_id: id_type::MerchantId,},+ InternalMerchantIdProfileId {+ merchant_id: id_type::MerchantId,+ profile_id: Option<id_type::ProfileId>,+ },NoAuth,}@@ -184,7 +189,8 @@ impl AuthenticationType {user_id: _,}| Self::MerchantJwtWithProfileId { merchant_id, .. }- | Self::WebhookAuth { merchant_id } => Some(merchant_id),+ | Self::WebhookAuth { merchant_id }+ | Self::InternalMerchantIdProfileId { merchant_id, .. } => Some(merchant_id),Self::AdminApiKey| Self::OrganizationJwt { .. }| Self::UserJwt { .. }@@ -1958,6 +1964,10 @@ impl<'a> HeaderMapStruct<'a> {})}+ pub fn get_header_value_by_key(&self, key: &str) -> Option<&str> {+ self.headers.get(key).and_then(|value| value.to_str().ok())+ }+pub fn get_auth_string_from_header(&self) -> RouterResult<&str> {self.headers.get(headers::AUTHORIZATION)@@ -2309,6 +2319,96 @@ where}}+/// InternalMerchantIdProfileIdAuth authentication which first tries to authenticate using `X-Internal-API-Key`,+/// `X-Merchant-Id` and `X-Profile-Id` headers. If any of these headers are missing,+/// it falls back to the provided authentication mechanism.+#[cfg(feature = "v1")]+pub struct InternalMerchantIdProfileIdAuth<F>(pub F);++#[cfg(feature = "v1")]+#[async_trait]+impl<A, F> AuthenticateAndFetch<AuthenticationData, A> for InternalMerchantIdProfileIdAuth<F>+where+ A: SessionStateInfo + Sync + Send,+ F: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send,+{+ async fn authenticate_and_fetch(+ &self,+ request_headers: &HeaderMap,+ state: &A,+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {+ if !state.conf().internal_merchant_id_profile_id_auth.enabled {+ return self.0.authenticate_and_fetch(request_headers, state).await;+ }+ let merchant_id = HeaderMapStruct::new(request_headers)+ .get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)+ .ok();+ let internal_api_key = HeaderMapStruct::new(request_headers)+ .get_header_value_by_key(headers::X_INTERNAL_API_KEY)+ .map(|s| s.to_string());+ let profile_id = HeaderMapStruct::new(request_headers)+ .get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)+ .ok();+ if let (Some(internal_api_key), Some(merchant_id), Some(profile_id)) =+ (internal_api_key, merchant_id, profile_id)+ {+ let config = state.conf();+ if internal_api_key+ != *config+ .internal_merchant_id_profile_id_auth+ .internal_api_key+ .peek()+ {+ return Err(errors::ApiErrorResponse::Unauthorized)+ .attach_printable("Internal API key authentication failed");+ }+ 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 _profile = state+ .store()+ .find_business_profile_by_merchant_id_profile_id(+ key_manager_state,+ &key_store,+ &merchant_id,+ &profile_id,+ )+ .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)?;+ let auth = AuthenticationData {+ merchant_account: merchant,+ key_store,+ profile_id: Some(profile_id.clone()),+ platform_merchant_account: None,+ };+ Ok((+ auth.clone(),+ AuthenticationType::InternalMerchantIdProfileId {+ merchant_id,+ profile_id: Some(profile_id),+ },+ ))+ } else {+ Ok(self+ .0+ .authenticate_and_fetch(request_headers, state)+ .await?)+ }+ }+}+#[derive(Debug)]#[cfg(feature = "v2")]pub struct MerchantIdAndProfileIdAuth {@@ -4362,6 +4462,41 @@ pub fn is_jwt_auth(headers: &HeaderMap) -> bool {}}+pub fn is_internal_api_key_merchant_id_profile_id_auth(+ headers: &HeaderMap,+ internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings,+) -> bool {+ internal_api_key_auth.enabled+ && headers.contains_key(headers::X_INTERNAL_API_KEY)+ && headers.contains_key(headers::X_MERCHANT_ID)+ && headers.contains_key(headers::X_PROFILE_ID)+}++#[cfg(feature = "v1")]+pub fn check_internal_api_key_auth<T>(+ headers: &HeaderMap,+ payload: &impl ClientSecretFetch,+ api_auth: ApiKeyAuth,+ internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings,+) -> RouterResult<(+ Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,+ api::AuthFlow,+)>+where+ T: SessionStateInfo + Sync + Send,+ ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,+{+ if is_internal_api_key_merchant_id_profile_id_auth(headers, internal_api_key_auth) {+ Ok((+ // HeaderAuth(api_auth) will never be called in this case as the internal auth will be checked first+ Box::new(InternalMerchantIdProfileIdAuth(HeaderAuth(api_auth))),+ api::AuthFlow::Merchant,+ ))+ } else {+ check_client_secret_and_get_auth(headers, payload, api_auth)+ }+}+pub async fn decode_jwt<T>(token: &str, state: &impl SessionStateInfo) -> RouterResult<T>whereT: serde::de::DeserializeOwned,diff --git a/loadtest/config/development.toml b/loadtest/config/development.tomlindex 6ce0a4b66e..93d4f00e01 100644--- a/loadtest/config/development.toml+++ b/loadtest/config/development.toml@@ -857,3 +857,8 @@ max_retry_count_for_thirty_day = 20[revenue_recovery.card_config.discover]max_retries_per_day = 20max_retry_count_for_thirty_day = 20++# Authentication to communicate between internal services using common_api_key, merchant id and profile id+[internal_merchant_id_profile_id_auth]+enabled = false # Enable or disable internal api key, merchant id and profile id based authentication+internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication\ No newline at end of file