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(events): add api auth type details to events (#2760)
Sampras Lopes10944937a025
diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rsindex 8a1bf3f6ae..75cb07de02 100644--- a/crates/router/src/compatibility/wrap.rs+++ b/crates/router/src/compatibility/wrap.rs@@ -28,7 +28,6 @@ whereQ: Serialize + std::fmt::Debug + 'a,S: TryFrom<Q> + Serialize,E: Serialize + error_stack::Context + actix_web::ResponseError + Clone,- U: auth::AuthInfo,error_stack::Report<E>: services::EmbedError,errors::ApiErrorResponse: ErrorSwitch<E>,T: std::fmt::Debug + Serialize,diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rsindex 5e031fd945..35eaf1edae 100644--- a/crates/router/src/events/api_logs.rs+++ b/crates/router/src/events/api_logs.rs@@ -1,16 +1,19 @@use router_env::{tracing_actix_web::RequestId, types::FlowMetric};-use serde::{Deserialize, Serialize};+use serde::Serialize;use time::OffsetDateTime;use super::{EventType, RawEvent};+use crate::services::authentication::AuthenticationType;-#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]+#[derive(Clone, Debug, Eq, PartialEq, Serialize)]pub struct ApiEvent {api_flow: String,created_at_timestamp: i128,request_id: String,latency: u128,status_code: i64,+ #[serde(flatten)]+ auth_type: AuthenticationType,request: serde_json::Value,response: Option<serde_json::Value>,}@@ -23,6 +26,7 @@ impl ApiEvent {status_code: i64,request: serde_json::Value,response: Option<serde_json::Value>,+ auth_type: AuthenticationType,) -> Self {Self {api_flow: api_flow.to_string(),@@ -32,6 +36,7 @@ impl ApiEvent {status_code,request,response,+ auth_type,}}}diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rsindex cb94312b0e..a1e657c7d9 100644--- a/crates/router/src/services/api.rs+++ b/crates/router/src/services/api.rs@@ -25,7 +25,7 @@ use serde_json::json;use tera::{Context, Tera};use self::request::{HeaderExt, RequestBuilderExt};-use super::authentication::{AuthInfo, AuthenticateAndFetch};+use super::authentication::AuthenticateAndFetch;use crate::{configs::settings::{Connectors, Settings},consts,@@ -761,7 +761,6 @@ whereQ: Serialize + Debug + 'a,T: Debug + Serialize,A: AppStateInfo + Clone,- U: AuthInfo,E: ErrorSwitch<OErr> + error_stack::Context,OErr: ResponseError + error_stack::Context,errors::ApiErrorResponse: ErrorSwitch<OErr>,@@ -782,12 +781,12 @@ where.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;// Currently auth failures are not recorded as API events- let auth_out = api_auth+ let (auth_out, auth_type) = api_auth.authenticate_and_fetch(request.headers(), &request_state).await.switch()?;- let merchant_id = auth_out+ let merchant_id = auth_type.get_merchant_id().unwrap_or("MERCHANT_ID_NOT_FOUND").to_string();@@ -841,6 +840,7 @@ wherestatus_code,serialized_request,serialized_response,+ auth_type,);match api_event.clone().try_into() {Ok(event) => {@@ -874,7 +874,6 @@ whereFut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,Q: Serialize + Debug + 'a,T: Debug + Serialize,- U: AuthInfo,A: AppStateInfo + Clone,ApplicationResponse<Q>: Debug,E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context,diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex eec872a9f3..faa7864aff 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -7,6 +7,7 @@ use error_stack::{report, IntoReport, ResultExt};use external_services::kms::{self, decrypt::KmsDecrypt};use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};use masking::{PeekInterface, StrongSecret};+use serde::Serialize;use crate::{configs::settings,@@ -21,11 +22,51 @@ use crate::{utils::OptionExt,};+#[derive(Clone, Debug)]pub struct AuthenticationData {pub merchant_account: domain::MerchantAccount,pub key_store: domain::MerchantKeyStore,}+#[derive(Clone, Debug, Eq, PartialEq, Serialize)]+#[serde(tag = "api_auth_type")]+pub enum AuthenticationType {+ ApiKey {+ merchant_id: String,+ key_id: String,+ },+ AdminApiKey,+ MerchantJWT {+ merchant_id: String,+ user_id: Option<String>,+ },+ MerchantID {+ merchant_id: String,+ },+ PublishableKey {+ merchant_id: String,+ },+ NoAuth,+}++impl AuthenticationType {+ pub fn get_merchant_id(&self) -> Option<&str> {+ match self {+ Self::ApiKey {+ merchant_id,+ key_id: _,+ }+ | Self::MerchantID { merchant_id }+ | Self::PublishableKey { merchant_id }+ | Self::MerchantJWT {+ merchant_id,+ user_id: _,+ } => Some(merchant_id.as_ref()),+ Self::AdminApiKey | Self::NoAuth => None,+ }+ }+}+pub trait AuthInfo {fn get_merchant_id(&self) -> Option<&str>;}@@ -46,13 +87,12 @@ impl AuthInfo for AuthenticationData {pub trait AuthenticateAndFetch<T, A>whereA: AppStateInfo,- T: AuthInfo,{async fn authenticate_and_fetch(&self,request_headers: &HeaderMap,state: &A,- ) -> RouterResult<T>;+ ) -> RouterResult<(T, AuthenticationType)>;}#[derive(Debug)]@@ -69,8 +109,8 @@ where&self,_request_headers: &HeaderMap,_state: &A,- ) -> RouterResult<()> {- Ok(())+ ) -> RouterResult<((), AuthenticationType)> {+ Ok(((), AuthenticationType::NoAuth))}}@@ -83,7 +123,7 @@ where&self,request_headers: &HeaderMap,state: &A,- ) -> RouterResult<AuthenticationData> {+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {let api_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?.trim();@@ -139,10 +179,17 @@ where.await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- Ok(AuthenticationData {+ let auth = AuthenticationData {merchant_account: merchant,key_store,- })+ };+ Ok((+ auth.clone(),+ AuthenticationType::ApiKey {+ merchant_id: auth.merchant_account.merchant_id.clone(),+ key_id: stored_api_key.key_id,+ },+ ))}}@@ -183,7 +230,7 @@ where&self,request_headers: &HeaderMap,state: &A,- ) -> RouterResult<()> {+ ) -> RouterResult<((), AuthenticationType)> {let request_admin_api_key =get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;let conf = state.conf();@@ -200,7 +247,7 @@ where.attach_printable("Admin Authentication Failure"))?;}- Ok(())+ Ok(((), AuthenticationType::AdminApiKey))}}@@ -216,7 +263,7 @@ where&self,_request_headers: &HeaderMap,state: &A,- ) -> RouterResult<AuthenticationData> {+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {let key_store = state.store().get_merchant_key_store_by_merchant_id(@@ -245,10 +292,16 @@ where}})?;- Ok(AuthenticationData {+ let auth = AuthenticationData {merchant_account: merchant,key_store,- })+ };+ Ok((+ auth.clone(),+ AuthenticationType::MerchantID {+ merchant_id: auth.merchant_account.merchant_id.clone(),+ },+ ))}}@@ -264,7 +317,7 @@ where&self,request_headers: &HeaderMap,state: &A,- ) -> RouterResult<AuthenticationData> {+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {let publishable_key =get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;@@ -279,6 +332,14 @@ wheree.change_context(errors::ApiErrorResponse::InternalServerError)}})+ .map(|auth| {+ (+ auth.clone(),+ AuthenticationType::PublishableKey {+ merchant_id: auth.merchant_account.merchant_id.clone(),+ },+ )+ })}}@@ -300,12 +361,12 @@ where&self,request_headers: &HeaderMap,state: &A,- ) -> RouterResult<()> {+ ) -> RouterResult<((), AuthenticationType)> {let mut token = get_jwt(request_headers)?;token = strip_jwt_token(token)?;decode_jwt::<JwtAuthPayloadFetchUnit>(token, state).await- .map(|_| ())+ .map(|_| ((), AuthenticationType::NoAuth))}}@@ -323,7 +384,7 @@ where&self,request_headers: &HeaderMap,state: &A,- ) -> RouterResult<AuthenticationData> {+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {let mut token = get_jwt(request_headers)?;token = strip_jwt_token(token)?;let payload = decode_jwt::<JwtAuthPayloadFetchMerchantAccount>(token, state).await?;@@ -343,10 +404,17 @@ where.await.change_context(errors::ApiErrorResponse::InvalidJwtToken)?;- Ok(AuthenticationData {+ let auth = AuthenticationData {merchant_account: merchant,key_store,- })+ };+ Ok((+ auth.clone(),+ AuthenticationType::MerchantJWT {+ merchant_id: auth.merchant_account.merchant_id.clone(),+ user_id: None,+ },+ ))}}