repo
stringclasses
1 value
instance_id
stringlengths
22
24
problem_statement
stringlengths
30
24.1k
patch
stringlengths
0
1.9M
test_patch
stringclasses
1 value
created_at
stringdate
2022-11-25 05:12:07
2025-06-13 10:24:29
hints_text
stringlengths
0
228k
base_commit
stringlengths
40
40
test_instructions
stringlengths
0
232k
filenames
listlengths
0
300
juspay/hyperswitch
juspay__hyperswitch-3433
Bug: [FEATURE] Update card_details for an existing mandate ### Feature Description There is an existing mandate, with current card details and the Customer for some reason wants to update his card details for that particular mandate. ### Possible Implementation The possible implementation for this would is, - while making a `/payments` call create the `Mandate_data` object with an `update_existing_mandate` field which would have the `current/existing mandate`. - if in the request we get the `update_existing_mandate` as some valid mandate for that particular merchant, we create a new Mandate on the connector's end and if that creation is a success, we revoke the Previous Mandate with the Previous Card Details on the connectors end - And then we'll map the `new_connector_mandate_id` with our existing `mandate_id` and update the following in the db - Create a new list that contains the `old_connector_mandate_id' for keeping a reference of older mandates that were revoked or need to be revoked ### TBDs - [ ] What do we do when there’s no revoke call supported by connector? > We add the task in process tracker - [ ] What if the revoke retries call fails even after adding the task to the process tracker? - [ ] How do we deal if there's a Connector Error while creating a mandate? - [ ] https://github.com/juspay/hyperswitch/issues/3465 - [ ] https://github.com/juspay/hyperswitch/pull/3452 - [ ] https://github.com/juspay/hyperswitch/issues/3464 - [ ] https://github.com/juspay/hyperswitch/issues/3538 ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 57c66dc5a7b..8c27f498d7a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -617,10 +617,18 @@ pub enum MandateReferenceId { NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns } -#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, + pub update_history: Option<Vec<UpdateHistory>>, +} + +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] +pub struct UpdateHistory { + pub connector_mandate_id: Option<String>, + pub payment_method_id: String, + pub original_payment_id: Option<String>, } impl MandateIds { @@ -637,6 +645,8 @@ impl MandateIds { #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { + /// A way to update the mandate's payment method details + pub update_mandate_id: Option<String>, /// A concent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used diff --git a/crates/data_models/src/mandates.rs b/crates/data_models/src/mandates.rs index afdcda3a40e..319a78cf661 100644 --- a/crates/data_models/src/mandates.rs +++ b/crates/data_models/src/mandates.rs @@ -9,6 +9,13 @@ use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use time::PrimitiveDateTime; +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub struct MandateDetails { + pub update_mandate_id: Option<String>, + pub mandate_type: Option<MandateDataType>, +} + #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum MandateDataType { @@ -16,6 +23,13 @@ pub enum MandateDataType { MultiUse(Option<MandateAmountData>), } +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +#[serde(untagged)] +pub enum MandateTypeDetails { + MandateType(MandateDataType), + MandateDetails(MandateDetails), +} #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: i64, @@ -29,6 +43,8 @@ pub struct MandateAmountData { // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, Clone)] pub struct MandateData { + /// A way to update the mandate's payment method details + pub update_mandate_id: Option<String>, /// A concent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used @@ -90,6 +106,7 @@ impl From<ApiMandateData> for MandateData { Self { customer_acceptance: value.customer_acceptance.map(|d| d.into()), mandate_type: value.mandate_type.map(|d| d.into()), + update_mandate_id: value.update_mandate_id, } } } diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs index 3e6ba9e37f8..e6b9950b459 100644 --- a/crates/data_models/src/payments/payment_attempt.rs +++ b/crates/data_models/src/payments/payment_attempt.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use super::PaymentIntent; -use crate::{errors, mandates::MandateDataType, ForeignIDRef}; +use crate::{errors, mandates::MandateTypeDetails, ForeignIDRef}; #[async_trait::async_trait] pub trait PaymentAttemptInterface { @@ -143,7 +143,7 @@ pub struct PaymentAttempt { pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, // providing a location to store mandate details intermediately for transaction - pub mandate_details: Option<MandateDataType>, + pub mandate_details: Option<MandateTypeDetails>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, // reference to the payment at connector side @@ -184,7 +184,7 @@ pub struct PaymentAttemptNew { pub attempt_id: String, pub status: storage_enums::AttemptStatus, pub amount: i64, - /// amount + surcharge_amount + tax_amount + /// amount + surcharge_amount + tax_amount /// This field will always be derived before updating in the Database pub net_amount: i64, pub currency: Option<storage_enums::Currency>, @@ -221,7 +221,7 @@ pub struct PaymentAttemptNew { pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - pub mandate_details: Option<MandateDataType>, + pub mandate_details: Option<MandateTypeDetails>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index a06937c99a6..babffdbc4a8 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -166,6 +166,17 @@ use diesel::{ expression::AsExpression, sql_types::Jsonb, }; + +#[derive( + serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, +)] +#[diesel(sql_type = Jsonb)] +#[serde(rename_all = "snake_case")] +pub struct MandateDetails { + pub update_mandate_id: Option<String>, + pub mandate_type: Option<MandateDataType>, +} + #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, )] @@ -185,6 +196,7 @@ where Ok(serde_json::from_value(value)?) } } + impl ToSql<Jsonb, diesel::pg::Pg> for MandateDataType where serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, @@ -199,6 +211,40 @@ where } } +#[derive( + serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, +)] +#[diesel(sql_type = Jsonb)] +#[serde(untagged)] +#[serde(rename_all = "snake_case")] +pub enum MandateTypeDetails { + MandateType(MandateDataType), + MandateDetails(MandateDetails), +} + +impl<DB: Backend> FromSql<Jsonb, DB> for MandateTypeDetails +where + serde_json::Value: FromSql<Jsonb, DB>, +{ + fn from_sql(bytes: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> { + let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?; + Ok(serde_json::from_value(value)?) + } +} +impl ToSql<Jsonb, diesel::pg::Pg> for MandateTypeDetails +where + serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>, +{ + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result { + let value = serde_json::to_value(self)?; + + // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends + // please refer to the diesel migration blog: + // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations + <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow()) + } +} + #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct MandateAmountData { pub amount: i64, diff --git a/crates/diesel_models/src/mandate.rs b/crates/diesel_models/src/mandate.rs index cc3474914c0..31c6ef62f2b 100644 --- a/crates/diesel_models/src/mandate.rs +++ b/crates/diesel_models/src/mandate.rs @@ -75,6 +75,12 @@ pub enum MandateUpdate { ConnectorReferenceUpdate { connector_mandate_ids: Option<pii::SecretSerdeValue>, }, + ConnectorMandateIdUpdate { + connector_mandate_id: Option<String>, + connector_mandate_ids: Option<pii::SecretSerdeValue>, + payment_method_id: String, + original_payment_id: Option<String>, + }, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] @@ -89,6 +95,9 @@ pub struct MandateUpdateInternal { mandate_status: Option<storage_enums::MandateStatus>, amount_captured: Option<i64>, connector_mandate_ids: Option<pii::SecretSerdeValue>, + connector_mandate_id: Option<String>, + payment_method_id: Option<String>, + original_payment_id: Option<String>, } impl From<MandateUpdate> for MandateUpdateInternal { @@ -98,16 +107,34 @@ impl From<MandateUpdate> for MandateUpdateInternal { mandate_status: Some(mandate_status), connector_mandate_ids: None, amount_captured: None, + connector_mandate_id: None, + payment_method_id: None, + original_payment_id: None, }, MandateUpdate::CaptureAmountUpdate { amount_captured } => Self { mandate_status: None, amount_captured, connector_mandate_ids: None, + connector_mandate_id: None, + payment_method_id: None, + original_payment_id: None, }, MandateUpdate::ConnectorReferenceUpdate { - connector_mandate_ids: connector_mandate_id, + connector_mandate_ids, + } => Self { + connector_mandate_ids, + ..Default::default() + }, + MandateUpdate::ConnectorMandateIdUpdate { + connector_mandate_id, + connector_mandate_ids, + payment_method_id, + original_payment_id, } => Self { - connector_mandate_ids: connector_mandate_id, + connector_mandate_id, + connector_mandate_ids, + payment_method_id: Some(payment_method_id), + original_payment_id, ..Default::default() }, } diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index d08c146b0b8..4a7603384c5 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -51,7 +51,7 @@ pub struct PaymentAttempt { pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, // providing a location to store mandate details intermediately for transaction - pub mandate_details: Option<storage_enums::MandateDataType>, + pub mandate_details: Option<storage_enums::MandateTypeDetails>, pub error_reason: Option<String>, pub multiple_capture_count: Option<i16>, // reference to the payment at connector side @@ -126,7 +126,7 @@ pub struct PaymentAttemptNew { pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - pub mandate_details: Option<storage_enums::MandateDataType>, + pub mandate_details: Option<storage_enums::MandateTypeDetails>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub multiple_capture_count: Option<i16>, diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index 5a1ea696c56..5a2226f0676 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -5,7 +5,7 @@ use common_enums::{ use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::{enums::MandateDataType, schema::payment_attempt, PaymentAttemptNew}; +use crate::{enums::MandateTypeDetails, schema::payment_attempt, PaymentAttemptNew}; #[derive( Clone, Debug, Default, diesel::Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize, @@ -50,7 +50,7 @@ pub struct PaymentAttemptBatchNew { pub business_sub_label: Option<String>, pub straight_through_algorithm: Option<serde_json::Value>, pub preprocessing_step_id: Option<String>, - pub mandate_details: Option<MandateDataType>, + pub mandate_details: Option<MandateTypeDetails>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, pub connector_transaction_id: Option<String>, diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 810e0ed1d28..aac150b5079 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -753,6 +753,7 @@ impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments:: user_agent: online.user_agent, }), }), + update_mandate_id: None, }); Ok(mandate_data) } diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index b6837d14f82..7299ef624d8 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -1,13 +1,13 @@ +pub mod helpers; pub mod utils; - use api_models::payments; use common_utils::{ext_traits::Encode, pii}; -use diesel_models::enums as storage_enums; +use diesel_models::{enums as storage_enums, Mandate}; use error_stack::{report, IntoReport, ResultExt}; use futures::future; use router_env::{instrument, logger, tracing}; -use super::payments::helpers; +use super::payments::helpers as payment_helper; use crate::{ core::{ errors::{self, RouterResponse, StorageErrorExt}, @@ -64,34 +64,17 @@ pub async fn revoke_mandate( common_enums::MandateStatus::Active | common_enums::MandateStatus::Inactive | common_enums::MandateStatus::Pending => { - let profile_id = if let Some(ref payment_id) = mandate.original_payment_id { - let pi = db - .find_payment_intent_by_payment_id_merchant_id( - payment_id, - &merchant_account.merchant_id, - merchant_account.storage_scheme, - ) - .await - .change_context(errors::ApiErrorResponse::PaymentNotFound)?; - let profile_id = pi.profile_id.clone().ok_or( - errors::ApiErrorResponse::BusinessProfileNotFound { - id: pi - .profile_id - .unwrap_or_else(|| "Profile id is Null".to_string()), - }, - )?; - Ok(profile_id) - } else { - Err(errors::ApiErrorResponse::PaymentNotFound) - }?; + let profile_id = + helpers::get_profile_id_for_mandate(&state, &merchant_account, mandate.clone()) + .await?; - let merchant_connector_account = helpers::get_merchant_connector_account( + let merchant_connector_account = payment_helper::get_merchant_connector_account( &state, &merchant_account.merchant_id, None, &key_store, &profile_id, - &mandate.connector, + &mandate.connector.clone(), mandate.merchant_connector_id.as_ref(), ) .await?; @@ -243,7 +226,72 @@ where _ => Some(router_data.request.get_payment_method_data()), } } +pub async fn update_mandate_procedure<F, FData>( + state: &AppState, + resp: types::RouterData<F, FData, types::PaymentsResponseData>, + mandate: Mandate, + merchant_id: &str, + pm_id: Option<String>, +) -> errors::RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> +where + FData: MandateBehaviour, +{ + let mandate_details = match &resp.response { + Ok(types::PaymentsResponseData::TransactionResponse { + mandate_reference, .. + }) => mandate_reference, + Ok(_) => Err(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Unexpected response received")?, + Err(_) => return Ok(resp), + }; + let old_record = payments::UpdateHistory { + connector_mandate_id: mandate.connector_mandate_id, + payment_method_id: mandate.payment_method_id, + original_payment_id: mandate.original_payment_id, + }; + + let mandate_ref = mandate + .connector_mandate_ids + .parse_value::<payments::ConnectorMandateReferenceId>("Connector Reference Id") + .change_context(errors::ApiErrorResponse::MandateDeserializationFailed)?; + + let mut update_history = mandate_ref.update_history.unwrap_or_default(); + update_history.push(old_record); + + let updated_mandate_ref = payments::ConnectorMandateReferenceId { + connector_mandate_id: mandate_details + .as_ref() + .and_then(|mandate_ref| mandate_ref.connector_mandate_id.clone()), + payment_method_id: pm_id.clone(), + update_history: Some(update_history), + }; + + let connector_mandate_ids = + Encode::<types::MandateReference>::encode_to_value(&updated_mandate_ref) + .change_context(errors::ApiErrorResponse::InternalServerError) + .map(masking::Secret::new)?; + + let _update_mandate_details = state + .store + .update_mandate_by_merchant_id_mandate_id( + merchant_id, + &mandate.mandate_id, + diesel_models::MandateUpdate::ConnectorMandateIdUpdate { + connector_mandate_id: mandate_details + .as_ref() + .and_then(|man_ref| man_ref.connector_mandate_id.clone()), + connector_mandate_ids: Some(connector_mandate_ids), + payment_method_id: pm_id + .unwrap_or("Error retrieving the payment_method_id".to_string()), + original_payment_id: Some(resp.payment_id.clone()), + }, + ) + .await + .change_context(errors::ApiErrorResponse::MandateUpdateFailed)?; + Ok(resp) +} pub async fn mandate_procedure<F, FData>( state: &AppState, mut resp: types::RouterData<F, FData, types::PaymentsResponseData>, @@ -324,7 +372,7 @@ where }) .transpose()?; - if let Some(new_mandate_data) = helpers::generate_mandate( + if let Some(new_mandate_data) = payment_helper::generate_mandate( resp.merchant_id.clone(), resp.payment_id.clone(), resp.connector.clone(), @@ -363,6 +411,8 @@ where api_models::payments::ConnectorMandateReferenceId { connector_mandate_id: connector_id.connector_mandate_id, payment_method_id: connector_id.payment_method_id, + update_history:None, + } ))) })); diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs new file mode 100644 index 00000000000..150130ed9e5 --- /dev/null +++ b/crates/router/src/core/mandate/helpers.rs @@ -0,0 +1,35 @@ +use common_utils::errors::CustomResult; +use diesel_models::Mandate; +use error_stack::ResultExt; + +use crate::{core::errors, routes::AppState, types::domain}; + +pub async fn get_profile_id_for_mandate( + state: &AppState, + merchant_account: &domain::MerchantAccount, + mandate: Mandate, +) -> CustomResult<String, errors::ApiErrorResponse> { + let profile_id = if let Some(ref payment_id) = mandate.original_payment_id { + let pi = state + .store + .find_payment_intent_by_payment_id_merchant_id( + payment_id, + &merchant_account.merchant_id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + let profile_id = + pi.profile_id + .clone() + .ok_or(errors::ApiErrorResponse::BusinessProfileNotFound { + id: pi + .profile_id + .unwrap_or_else(|| "Profile id is Null".to_string()), + })?; + Ok(profile_id) + } else { + Err(errors::ApiErrorResponse::PaymentNotFound) + }?; + Ok(profile_id) +} diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 3dbd6fcb215..e08dbc61f5e 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1823,14 +1823,24 @@ pub async fn list_payment_methods( } else { api_surcharge_decision_configs::MerchantSurchargeConfigs::default() }; + print!("PAMT{:?}", payment_attempt); Ok(services::ApplicationResponse::Json( api::PaymentMethodListResponse { redirect_url: merchant_account.return_url, merchant_name: merchant_account.merchant_name, payment_type, payment_methods: payment_method_responses, - mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map( - |d| match d { + mandate_payment: payment_attempt + .and_then(|inner| inner.mandate_details) + .and_then(|man_type_details| match man_type_details { + data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => { + Some(mandate_type) + } + data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => { + mandate_details.mandate_type + } + }) + .map(|d| match d { data_models::mandates::MandateDataType::SingleUse(i) => { api::MandateType::SingleUse(api::MandateAmountData { amount: i.amount, @@ -1852,8 +1862,7 @@ pub async fn list_payment_methods( data_models::mandates::MandateDataType::MultiUse(None) => { api::MandateType::MultiUse(None) } - }, - ), + }), show_surcharge_breakup_screen: merchant_surcharge_configs .show_surcharge_breakup_screen .unwrap_or_default(), diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index d6343ed871b..8b0b54158fd 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -1,9 +1,10 @@ use async_trait::async_trait; +use error_stack::{IntoReport, ResultExt}; use super::{ConstructFlowSpecificData, Feature}; use crate::{ core::{ - errors::{self, ConnectorErrorExt, RouterResult}, + errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, payments::{ self, access_token, customers, helpers, tokenization, transformers, PaymentData, @@ -65,16 +66,16 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup types::SetupMandateRequestData, types::PaymentsResponseData, > = connector.connector.get_connector_integration(); + let resp = services::execute_connector_processing_step( state, connector_integration, &self, - call_connector_action, + call_connector_action.clone(), connector_request, ) .await .to_setup_mandate_failed_response()?; - let pm_id = Box::pin(tokenization::save_payment_method( state, connector, @@ -86,14 +87,84 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup )) .await?; - mandate::mandate_procedure( - state, - resp, - maybe_customer, - pm_id, - connector.merchant_connector_id.clone(), - ) - .await + if let Some(mandate_id) = self + .request + .setup_mandate_details + .as_ref() + .and_then(|mandate_data| mandate_data.update_mandate_id.clone()) + { + let mandate = state + .store + .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &mandate_id) + .await + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + + let profile_id = mandate::helpers::get_profile_id_for_mandate( + state, + merchant_account, + mandate.clone(), + ) + .await?; + match resp.response { + Ok(types::PaymentsResponseData::TransactionResponse { .. }) => { + let connector_integration: services::BoxedConnectorIntegration< + '_, + types::api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > = connector.connector.get_connector_integration(); + let merchant_connector_account = helpers::get_merchant_connector_account( + state, + &merchant_account.merchant_id, + None, + key_store, + &profile_id, + &mandate.connector, + mandate.merchant_connector_id.as_ref(), + ) + .await?; + + let router_data = mandate::utils::construct_mandate_revoke_router_data( + merchant_connector_account, + merchant_account, + mandate.clone(), + ) + .await?; + + let _response = services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + call_connector_action, + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + // TODO:Add the revoke mandate task to process tracker + mandate::update_mandate_procedure( + state, + resp, + mandate, + &merchant_account.merchant_id, + pm_id, + ) + .await + } + Ok(_) => Err(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Unexpected response received")?, + Err(_) => Ok(resp), + } + } else { + mandate::mandate_procedure( + state, + resp, + maybe_customer, + pm_id, + connector.merchant_connector_id.clone(), + ) + .await + } } async fn add_access_token<'a>( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 0cbed255348..520582eb22f 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -840,7 +840,7 @@ fn validate_new_mandate_request( let mandate_details = match mandate_data.mandate_type { Some(api_models::payments::MandateType::SingleUse(details)) => Some(details), Some(api_models::payments::MandateType::MultiUse(details)) => details, - None => None, + _ => None, }; mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)| utils::when (start_date >= end_date, || { diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index c81145c5de7..14fc28d6723 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -431,7 +431,29 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> // The operation merges mandate data from both request and payment_attempt setup_mandate = setup_mandate.map(|mut sm| { - sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type); + sm.mandate_type = payment_attempt + .mandate_details + .clone() + .and_then(|mandate| match mandate { + data_models::mandates::MandateTypeDetails::MandateType(mandate_type) => { + Some(mandate_type) + } + data_models::mandates::MandateTypeDetails::MandateDetails(mandate_details) => { + mandate_details.mandate_type + } + }) + .or(sm.mandate_type); + sm.update_mandate_id = payment_attempt + .mandate_details + .clone() + .and_then(|mandate| match mandate { + data_models::mandates::MandateTypeDetails::MandateType(_) => None, + data_models::mandates::MandateTypeDetails::MandateDetails(update_id) => { + Some(update_id.update_mandate_id) + } + }) + .flatten() + .or(sm.update_mandate_id); sm }); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 2b25a74deb1..d02ad15fbd6 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -3,7 +3,10 @@ use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; -use data_models::{mandates::MandateData, payments::payment_attempt::PaymentAttempt}; +use data_models::{ + mandates::{MandateData, MandateDetails, MandateTypeDetails}, + payments::payment_attempt::PaymentAttempt, +}; use diesel_models::ephemeral_key; use error_stack::{self, ResultExt}; use masking::PeekInterface; @@ -255,7 +258,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment { payment_id: payment_id.clone(), })?; - + // connector mandate reference update history let mandate_id = request .mandate_id .as_ref() @@ -284,10 +287,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> api_models::payments::MandateIds { mandate_id: mandate_obj.mandate_id, mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - api_models::payments::ConnectorMandateReferenceId { - connector_mandate_id: connector_id.connector_mandate_id, - payment_method_id: connector_id.payment_method_id, - }, + api_models::payments::ConnectorMandateReferenceId{ + connector_mandate_id: connector_id.connector_mandate_id, + payment_method_id: connector_id.payment_method_id, + update_history: None + } )) } }), @@ -701,6 +705,35 @@ impl PaymentCreate { .surcharge_details .and_then(|surcharge_details| surcharge_details.tax_amount); + if request.mandate_data.as_ref().map_or(false, |mandate_data| { + mandate_data.update_mandate_id.is_some() && mandate_data.mandate_type.is_some() + }) { + Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})? + } + + let mandate_dets = if let Some(update_id) = request + .mandate_data + .as_ref() + .and_then(|inner| inner.update_mandate_id.clone()) + { + let mandate_data = MandateDetails { + update_mandate_id: Some(update_id), + mandate_type: None, + }; + Some(MandateTypeDetails::MandateDetails(mandate_data)) + } else { + // let mandate_type: data_models::mandates::MandateDataType = + + let mandate_data = MandateDetails { + update_mandate_id: None, + mandate_type: request + .mandate_data + .as_ref() + .and_then(|inner| inner.mandate_type.clone().map(Into::into)), + }; + Some(MandateTypeDetails::MandateDetails(mandate_data)) + }; + Ok(( storage::PaymentAttemptNew { payment_id: payment_id.to_string(), @@ -727,10 +760,7 @@ impl PaymentCreate { business_sub_label: request.business_sub_label.clone(), surcharge_amount, tax_amount, - mandate_details: request - .mandate_data - .as_ref() - .and_then(|inner| inner.mandate_type.clone().map(Into::into)), + mandate_details: mandate_dets, ..storage::PaymentAttemptNew::default() }, additional_pm_data, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index e002b92d181..015ef5cea6e 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -255,10 +255,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> api_models::payments::MandateIds { mandate_id: mandate_obj.mandate_id, mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - api_models::payments::ConnectorMandateReferenceId { - connector_mandate_id: connector_id.connector_mandate_id, - payment_method_id: connector_id.payment_method_id, - }, + api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None }, )) } }), diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5f0c702a29d..61917fdcd2e 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -636,6 +636,7 @@ where api::MandateType::MultiUse(None) } }), + update_mandate_id: d.update_mandate_id, }), auth_flow == services::AuthFlow::Merchant, ) diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index fcd71719657..0cf5cabf2e4 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -202,6 +202,18 @@ impl MandateInterface for MockDb { } => { mandate.connector_mandate_ids = connector_mandate_ids; } + + diesel_models::MandateUpdate::ConnectorMandateIdUpdate { + connector_mandate_id, + connector_mandate_ids, + payment_method_id, + original_payment_id, + } => { + mandate.connector_mandate_ids = connector_mandate_ids; + mandate.connector_mandate_id = connector_mandate_id; + mandate.payment_method_id = payment_method_id; + mandate.original_payment_id = original_payment_id + } } Ok(mandate.clone()) } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 307dff55071..bc8ab2e05e7 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1674,7 +1674,7 @@ pub fn build_redirection_form( // Initialize the ThreeDSService const threeDS = gateway.get3DSecure(); - + const options = {{ customerVaultId: '{customer_vault_id}', currency: '{currency}', diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 786a8c55182..41aefc9026d 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -323,6 +323,7 @@ impl ForeignFrom<api_models::payments::MandateData> for data_models::mandates::M data_models::mandates::MandateDataType::MultiUse(None) } }), + update_mandate_id: d.update_mandate_id, } } } diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index f8f752c6bc8..b8d71cb32b7 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -2,7 +2,7 @@ use api_models::enums::{AuthenticationType, Connector, PaymentMethod, PaymentMet use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found}; use data_models::{ errors, - mandates::{MandateAmountData, MandateDataType}, + mandates::{MandateAmountData, MandateDataType, MandateDetails, MandateTypeDetails}, payments::{ payment_attempt::{ PaymentAttempt, PaymentAttemptInterface, PaymentAttemptNew, PaymentAttemptUpdate, @@ -14,6 +14,7 @@ use data_models::{ use diesel_models::{ enums::{ MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType, + MandateDetails as DieselMandateDetails, MandateTypeDetails as DieselMandateTypeOrDetails, MerchantStorageScheme, }, kv, @@ -999,6 +1000,50 @@ impl DataModelExt for MandateAmountData { } } } +impl DataModelExt for MandateDetails { + type StorageModel = DieselMandateDetails; + fn to_storage_model(self) -> Self::StorageModel { + DieselMandateDetails { + update_mandate_id: self.update_mandate_id, + mandate_type: self + .mandate_type + .map(|mand_type| mand_type.to_storage_model()), + } + } + fn from_storage_model(storage_model: Self::StorageModel) -> Self { + Self { + update_mandate_id: storage_model.update_mandate_id, + mandate_type: storage_model + .mandate_type + .map(MandateDataType::from_storage_model), + } + } +} +impl DataModelExt for MandateTypeDetails { + type StorageModel = DieselMandateTypeOrDetails; + + fn to_storage_model(self) -> Self::StorageModel { + match self { + Self::MandateType(mandate_type) => { + DieselMandateTypeOrDetails::MandateType(mandate_type.to_storage_model()) + } + Self::MandateDetails(mandate_details) => { + DieselMandateTypeOrDetails::MandateDetails(mandate_details.to_storage_model()) + } + } + } + + fn from_storage_model(storage_model: Self::StorageModel) -> Self { + match storage_model { + DieselMandateTypeOrDetails::MandateType(data) => { + Self::MandateType(MandateDataType::from_storage_model(data)) + } + DieselMandateTypeOrDetails::MandateDetails(data) => { + Self::MandateDetails(MandateDetails::from_storage_model(data)) + } + } + } +} impl DataModelExt for MandateDataType { type StorageModel = DieselMandateType; @@ -1123,7 +1168,7 @@ impl DataModelExt for PaymentAttempt { preprocessing_step_id: storage_model.preprocessing_step_id, mandate_details: storage_model .mandate_details - .map(MandateDataType::from_storage_model), + .map(MandateTypeDetails::from_storage_model), error_reason: storage_model.error_reason, multiple_capture_count: storage_model.multiple_capture_count, connector_response_reference_id: storage_model.connector_response_reference_id, @@ -1231,7 +1276,7 @@ impl DataModelExt for PaymentAttemptNew { preprocessing_step_id: storage_model.preprocessing_step_id, mandate_details: storage_model .mandate_details - .map(MandateDataType::from_storage_model), + .map(MandateTypeDetails::from_storage_model), error_reason: storage_model.error_reason, connector_response_reference_id: storage_model.connector_response_reference_id, multiple_capture_count: storage_model.multiple_capture_count, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 7858029961a..09cb5fe1404 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -9026,6 +9026,11 @@ "MandateData": { "type": "object", "properties": { + "update_mandate_id": { + "type": "string", + "description": "A way to update the mandate's payment method details", + "nullable": true + }, "customer_acceptance": { "allOf": [ {
2024-01-24T18:22:44Z
## Description Update card_details for an existing mandate ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
3fbffdc242dafe7983c542573b7c6362f99331e6
- Create an MA and MCA(for connectors that support mandate) - Create a mandate payment with payment_type as `setup_mandate` - Now update the new card details with `mandate_data` with `mandate_type` as ``` "mandate_data": { "customer_acceptance" :.. "update_mandate_id":"{{existing_mandate_id}}" } ``` - The card gets updated for the existing mandate_id <img width="1195" alt="Screenshot 2024-01-25 at 12 08 25 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/0a093794-7fda-4016-a7d8-600f4608a658"> - List mandate for customer with that mandate_id <img width="1195" alt="Screenshot 2024-01-25 at 12 11 03 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/1b2de9b4-f640-4d83-abf3-8e5843ac4c78"> - Also the `connector_mandate_id` would we updated in the mandate table with all the past records with its past `payment_method_id` as well as `old_connector_mandate_id`
[ "crates/api_models/src/payments.rs", "crates/data_models/src/mandates.rs", "crates/data_models/src/payments/payment_attempt.rs", "crates/diesel_models/src/enums.rs", "crates/diesel_models/src/mandate.rs", "crates/diesel_models/src/payment_attempt.rs", "crates/diesel_models/src/user/sample_data.rs", "c...
juspay/hyperswitch
juspay__hyperswitch-3483
Bug: adding dispute_id to Kafka events
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql index 0fe194a0e67..ad0fe6d778f 100644 --- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql +++ b/crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql @@ -18,7 +18,8 @@ CREATE TABLE hyperswitch.api_events_queue on cluster '{cluster}' ( `created_at` DateTime CODEC(T64, LZ4), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) ENGINE = Kafka SETTINGS kafka_broker_list = 'hyper-c1-kafka-brokers.kafka-cluster.svc.cluster.local:9092', kafka_topic_list = 'hyperswitch-api-log-events', kafka_group_name = 'hyper-c1', @@ -81,7 +82,8 @@ CREATE TABLE hyperswitch.api_events_dist on cluster '{cluster}' ( `created_at` DateTime64(3), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) ENGINE = Distributed('{cluster}', 'hyperswitch', 'api_events_clustered', rand()); CREATE MATERIALIZED VIEW hyperswitch.api_events_mv on cluster '{cluster}' TO hyperswitch.api_events_dist ( @@ -105,7 +107,8 @@ CREATE MATERIALIZED VIEW hyperswitch.api_events_mv on cluster '{cluster}' TO hyp `created_at` DateTime64(3), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -158,7 +161,7 @@ WHERE length(_error) > 0 ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `url_path` LowCardinality(Nullable(String)); ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `event_type` LowCardinality(Nullable(String)); - +ALTER TABLE hyperswitch.api_events_clustered on cluster '{cluster}' ADD COLUMN `dispute_id` Nullable(String); CREATE TABLE hyperswitch.api_audit_log ON CLUSTER '{cluster}' ( `merchant_id` LowCardinality(String), @@ -209,7 +212,8 @@ CREATE MATERIALIZED VIEW hyperswitch.api_audit_log_mv ON CLUSTER `{cluster}` TO `created_at` DateTime64(3), `latency` Nullable(UInt128), `user_agent` Nullable(String), - `ip_addr` Nullable(String) + `ip_addr` Nullable(String), + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -232,6 +236,7 @@ SELECT created_at, latency, user_agent, - ip_addr + ip_addr, + dispute_id FROM hyperswitch.api_events_queue WHERE length(_error) = 0 \ No newline at end of file diff --git a/crates/analytics/docs/clickhouse/scripts/api_events.sql b/crates/analytics/docs/clickhouse/scripts/api_events.sql index c3fc3d7b06d..49a6472eaa4 100644 --- a/crates/analytics/docs/clickhouse/scripts/api_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/api_events.sql @@ -23,7 +23,8 @@ CREATE TABLE api_events_queue ( `ip_addr` String, `hs_latency` Nullable(UInt128), `http_method` LowCardinality(String), - `url_path` String + `url_path` String, + `dispute_id` Nullable(String) ) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-api-log-events', kafka_group_name = 'hyper-c1', @@ -57,6 +58,7 @@ CREATE TABLE api_events_dist ( `hs_latency` Nullable(UInt128), `http_method` LowCardinality(String), `url_path` String, + `dispute_id` Nullable(String) INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1, INDEX apiIndex api_flow TYPE bloom_filter GRANULARITY 1, INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 @@ -92,7 +94,8 @@ CREATE MATERIALIZED VIEW api_events_mv TO api_events_dist ( `ip_addr` String, `hs_latency` Nullable(UInt128), `http_method` LowCardinality(String), - `url_path` String + `url_path` String, + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -120,7 +123,8 @@ SELECT ip_addr, hs_latency, http_method, - url_path + url_path, + dispute_id FROM api_events_queue where length(_error) = 0; diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index a8185d2d241..ae0525ac609 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -1,5 +1,6 @@ pub mod connector_onboarding; pub mod customer; +pub mod dispute; pub mod gsm; mod locker_migration; pub mod payment; @@ -44,8 +45,6 @@ impl_misc_api_event_type!( RetrievePaymentLinkResponse, MandateListConstraints, CreateFileResponse, - DisputeResponse, - SubmitEvidenceRequest, MerchantConnectorResponse, MerchantConnectorId, MandateResponse, diff --git a/crates/api_models/src/events/dispute.rs b/crates/api_models/src/events/dispute.rs new file mode 100644 index 00000000000..101dba3ca02 --- /dev/null +++ b/crates/api_models/src/events/dispute.rs @@ -0,0 +1,25 @@ +use common_utils::events::{ApiEventMetric, ApiEventsType}; + +use super::{DisputeResponse, DisputeResponsePaymentsRetrieve, SubmitEvidenceRequest}; + +impl ApiEventMetric for SubmitEvidenceRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +} +impl ApiEventMetric for DisputeResponsePaymentsRetrieve { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +} +impl ApiEventMetric for DisputeResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +} diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index c2bf50d96c3..e755e0f9c4c 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -50,6 +50,9 @@ pub enum ApiEventsType { RustLocker, FraudCheck, Recon, + Dispute { + dispute_id: String, + }, } impl ApiEventMetric for serde_json::Value {} diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs index 78a66d2f04e..3d74a028840 100644 --- a/crates/router/src/events/api_logs.rs +++ b/crates/router/src/events/api_logs.rs @@ -114,7 +114,6 @@ impl_misc_api_event_type!( CreateFileRequest, FileId, AttachEvidenceRequest, - DisputeId, PaymentLinkFormData, ConfigUpdate ); @@ -142,3 +141,11 @@ impl ApiEventMetric for PaymentsRedirectResponseData { }) } } + +impl ApiEventMetric for DisputeId { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Dispute { + dispute_id: self.dispute_id.clone(), + }) + } +}
2024-01-24T12:48:32Z
## Description adding dispute id to hyperswitch-api-log-events ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
c9d41e2169decf3e9a26999c37fe81b6a8c0362f
check for dispute_id in topic = ```hyperswitch-api-log-events``` via loki
[ "crates/analytics/docs/clickhouse/cluster_setup/scripts/api_event_logs.sql", "crates/analytics/docs/clickhouse/scripts/api_events.sql", "crates/api_models/src/events.rs", "crates/api_models/src/events/dispute.rs", "crates/common_utils/src/events.rs", "crates/router/src/events/api_logs.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3448
Bug: [FIX] empty list of payment attempt on payments retrieve When you do a `PaymentsRetrieve` with a KV enabled merchant the `PaymentAttempts` list will be empty which is not expected
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index f8f752c6bc8..ce2c46bfe1d 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -931,12 +931,23 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } MerchantStorageScheme::RedisKv => { let key = format!("mid_{merchant_id}_pid_{payment_id}"); - - kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key) - .await - .change_context(errors::StorageError::KVError)? - .try_into_scan() - .change_context(errors::StorageError::KVError) + Box::pin(try_redis_get_else_try_database_get( + async { + kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key) + .await? + .try_into_scan() + }, + || async { + self.router_store + .find_attempts_by_merchant_id_payment_id( + merchant_id, + payment_id, + storage_scheme, + ) + .await + }, + )) + .await } } } diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 9339b11a9b9..ad57ad403d4 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -131,7 +131,16 @@ where } KvOperation::Scan(pattern) => { - let result: Vec<T> = redis_conn.hscan_and_deserialize(key, pattern, None).await?; + let result: Vec<T> = redis_conn + .hscan_and_deserialize(key, pattern, None) + .await + .and_then(|result| { + if result.is_empty() { + Err(RedisError::NotFound).into_report() + } else { + Ok(result) + } + })?; Ok(KvResult::Scan(result)) }
2024-01-24T10:22:44Z
## Description <!-- Describe your changes in detail --> This fixes payments attempts being empty on `PaymentsRetrieve` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This fixes PaymentAttempts being empty on a case where data is directly inserted into the DB or the TTL has expired on Redis. #
3f343d36bff7ce8f73602a2391d205367d5581c7
- Make a payment. - Do `PaymentsRetrieve` with `expand_attempts=true` ```bash curl --location 'http://localhost:8080/payments/pay_QJ9r33h2IiJz15brygDm?expand_attempts=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_6GYF6ws2zde4cDNPtKRKdLbYaY1Ekz3MtH2S9B8Zkb0aZIuXh4NlWICzdw5kTmHY'** ```
[ "crates/storage_impl/src/payments/payment_attempt.rs", "crates/storage_impl/src/redis/kv_store.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3274
Bug: Implement HashiCorp Vault support in the core application
diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 9bf4916eec3..f5fc4854086 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -38,3 +38,12 @@ pub mod metrics { #[cfg(feature = "kms")] histogram_metric!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for KMS encryption time (in sec) } + +// Mutually Exclusive - Feature Flags +// +// This are some feature flags that shouldn't be used together + +#[cfg(all(feature = "kms", feature = "hashicorp-vault"))] +compile_error!( + "feature \"kms\" and feature \"hashicorp-vault\" cannot be enabled at the same time" +); diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 72e3de0bf77..31282f7d734 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1446,9 +1446,9 @@ impl<F> resource_id: types::ResponseId::NoResponseId, redirection_data, mandate_reference: None, - connector_metadata: Some( - serde_json::json!({"three_ds_data":three_ds_data}), - ), + connector_metadata: Some(serde_json::json!({ + "three_ds_data": three_ds_data + })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 8beb81d9236..0abe1fff42c 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -2015,9 +2015,9 @@ impl<F> resource_id: types::ResponseId::NoResponseId, redirection_data, mandate_reference: None, - connector_metadata: Some( - serde_json::json!({"three_ds_data":three_ds_data}), - ), + connector_metadata: Some(serde_json::json!({ + "three_ds_data": three_ds_data + })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None,
2024-01-24T10:17:59Z
…d together ## Description Add compiler error when `kms` and `hashicorp-vault` feature flag are enabled together. <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
3f343d36bff7ce8f73602a2391d205367d5581c7
[ "crates/external_services/src/lib.rs", "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cybersource/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3419
Bug: Logging framework - Add a endrequest log line which should be a common line for accumulating all parameters Currently we use the `EndRequest` filter by actix to rely on this, but we need a log line that represents a request uniquely & contains all the key metadata about the request the list of fields that we need - Flow (already present) - payment_id - connector_name - payment_method
diff --git a/crates/drainer/src/query.rs b/crates/drainer/src/query.rs index f79291f3eae..a1e04fb6d0f 100644 --- a/crates/drainer/src/query.rs +++ b/crates/drainer/src/query.rs @@ -37,7 +37,7 @@ impl ExecuteQuery for kv::DBOperation { ]; let (result, execution_time) = - common_utils::date_time::time_it(|| self.execute(&conn)).await; + Box::pin(common_utils::date_time::time_it(|| self.execute(&conn))).await; push_drainer_delay(pushed_at, operation, table, tags); metrics::QUERY_EXECUTION_TIME.record(&metrics::CONTEXT, execution_time, tags); diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 712ae9e4035..968e6cb07d6 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -245,7 +245,13 @@ pub async fn update_customer_payment_method( .as_ref() .map(|card_network| card_network.to_string()), }; - add_payment_method(state, new_pm, &merchant_account, &key_store).await + Box::pin(add_payment_method( + state, + new_pm, + &merchant_account, + &key_store, + )) + .await } // Wrapper function to switch lockers diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 15d88c94660..f52bce46d8e 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -81,11 +81,11 @@ where ) .await? } else { - save_in_locker( + Box::pin(save_in_locker( state, merchant_account, payment_method_create_request.to_owned(), - ) + )) .await? }; diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index c38a4dc85b5..7b1aba14106 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -267,5 +267,6 @@ pub fn get_application_builder( .wrap(middleware::default_response_headers()) .wrap(middleware::RequestId) .wrap(cors::cors()) + .wrap(middleware::LogSpanInitializer) .wrap(router_env::tracing_actix_web::TracingLogger::default()) } diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs index c6c94d3a78e..1feba66a34f 100644 --- a/crates/router/src/middleware.rs +++ b/crates/router/src/middleware.rs @@ -1,3 +1,4 @@ +use router_env::tracing::{field::Empty, Instrument}; /// Middleware to include request ID in response header. pub struct RequestId; @@ -48,20 +49,23 @@ where let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>(); let response_fut = self.service.call(req); - Box::pin(async move { - let request_id = request_id_fut.await?; - let request_id = request_id.as_hyphenated().to_string(); - if let Some(upstream_request_id) = old_x_request_id { - router_env::logger::info!(?request_id, ?upstream_request_id); + Box::pin( + async move { + let request_id = request_id_fut.await?; + let request_id = request_id.as_hyphenated().to_string(); + if let Some(upstream_request_id) = old_x_request_id { + router_env::logger::info!(?request_id, ?upstream_request_id); + } + let mut response = response_fut.await?; + response.headers_mut().append( + http::header::HeaderName::from_static("x-request-id"), + http::HeaderValue::from_str(&request_id)?, + ); + + Ok(response) } - let mut response = response_fut.await?; - response.headers_mut().append( - http::header::HeaderName::from_static("x-request-id"), - http::HeaderValue::from_str(&request_id)?, - ); - - Ok(response) - }) + .in_current_span(), + ) } } @@ -81,3 +85,67 @@ pub fn default_response_headers() -> actix_web::middleware::DefaultHeaders { .add((header::STRICT_TRANSPORT_SECURITY, "max-age=31536000")) .add((header::VIA, "HyperSwitch")) } + +/// Middleware to build a TOP level domain span for each request. +pub struct LogSpanInitializer; + +impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for LogSpanInitializer +where + S: actix_web::dev::Service< + actix_web::dev::ServiceRequest, + Response = actix_web::dev::ServiceResponse<B>, + Error = actix_web::Error, + >, + S::Future: 'static, + B: 'static, +{ + type Response = actix_web::dev::ServiceResponse<B>; + type Error = actix_web::Error; + type Transform = LogSpanInitializerMiddleware<S>; + type InitError = (); + type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>; + + fn new_transform(&self, service: S) -> Self::Future { + std::future::ready(Ok(LogSpanInitializerMiddleware { service })) + } +} + +pub struct LogSpanInitializerMiddleware<S> { + service: S, +} + +impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> + for LogSpanInitializerMiddleware<S> +where + S: actix_web::dev::Service< + actix_web::dev::ServiceRequest, + Response = actix_web::dev::ServiceResponse<B>, + Error = actix_web::Error, + >, + S::Future: 'static, + B: 'static, +{ + type Response = actix_web::dev::ServiceResponse<B>; + type Error = actix_web::Error; + type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; + + actix_web::dev::forward_ready!(service); + + // TODO: have a common source of truth for the list of top level fields + // /crates/router_env/src/logger/storage.rs also has a list of fields called PERSISTENT_KEYS + fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future { + let response_fut = self.service.call(req); + + Box::pin( + response_fut.instrument( + router_env::tracing::info_span!( + "golden_log_line", + payment_id = Empty, + merchant_id = Empty, + connector_name = Empty + ) + .or_current(), + ), + ) + } +} diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index ab404125a38..f5a6a49b9c9 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -520,7 +520,7 @@ pub async fn business_profile_update( let flow = Flow::BusinessProfileUpdate; let (merchant_id, profile_id) = path.into_inner(); - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -535,7 +535,7 @@ pub async fn business_profile_update( req.headers(), ), api_locking::LockAction::NotApplicable, - ) + )) .await } #[instrument(skip_all, fields(flow = ?Flow::BusinessProfileDelete))] diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 468d202b94c..342fe23c38a 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -75,7 +75,7 @@ pub async fn revoke_mandate( let mandate_id = mandates::MandateId { mandate_id: path.into_inner(), }; - api::server_wrap( + Box::pin(api::server_wrap( flow, state, &req, @@ -85,7 +85,7 @@ pub async fn revoke_mandate( }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, - ) + )) .await } /// Mandates - List Mandates diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 6ef5de886be..55564a6386f 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -44,7 +44,13 @@ pub async fn create_payment_method_api( &req, json_payload.into_inner(), |state, auth, req| async move { - cards::add_payment_method(state, req, &auth.merchant_account, &auth.key_store).await + Box::pin(cards::add_payment_method( + state, + req, + &auth.merchant_account, + &auth.key_store, + )) + .await }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index ad463fcf2b9..307dff55071 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1131,7 +1131,6 @@ where status_code = response_code, time_taken_ms = request_duration.as_millis(), ); - res } diff --git a/crates/router_env/src/logger/storage.rs b/crates/router_env/src/logger/storage.rs index 51e701213b9..961a77c65aa 100644 --- a/crates/router_env/src/logger/storage.rs +++ b/crates/router_env/src/logger/storage.rs @@ -92,6 +92,8 @@ impl Visit for Storage<'_> { } } +const PERSISTENT_KEYS: [&str; 3] = ["payment_id", "connector_name", "merchant_id"]; + impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S> for StorageSubscription { @@ -99,6 +101,7 @@ impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(id).expect("No span"); + let mut extensions = span.extensions_mut(); let mut visitor = if let Some(parent_span) = span.parent() { let mut extensions = parent_span.extensions_mut(); @@ -110,7 +113,6 @@ impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer Storage::default() }; - let mut extensions = span.extensions_mut(); attrs.record(&mut visitor); extensions.insert(visitor); } @@ -150,6 +152,18 @@ impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer .unwrap_or(0) }; + if let Some(s) = span.extensions().get::<Storage<'_>>() { + s.values.iter().for_each(|(k, v)| { + if PERSISTENT_KEYS.contains(k) { + span.parent().and_then(|p| { + p.extensions_mut() + .get_mut::<Storage<'_>>() + .map(|s| s.values.insert(k, v.to_owned())) + }); + } + }) + }; + let mut extensions_mut = span.extensions_mut(); #[allow(clippy::expect_used)] let visitor = extensions_mut diff --git a/docker-compose-development.yml b/docker-compose-development.yml index 5a3eca4cdf3..665bdf2f05d 100644 --- a/docker-compose-development.yml +++ b/docker-compose-development.yml @@ -31,7 +31,7 @@ services: networks: - router_net ports: - - "6379" + - "6379:6379" migration_runner: image: rust:latest diff --git a/docker-compose.yml b/docker-compose.yml index 9f8e7bb4efb..3839269a522 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -27,7 +27,7 @@ services: networks: - router_net ports: - - "6379" + - "6379:6379" migration_runner: image: rust:latest
2024-01-24T06:55:33Z
## Description <!-- Describe your changes in detail --> - Create a request middleware to create a top level span consisting of all the metadata fields - Update the subscriber layer to propogate the metadata fields to the top layer ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> - Currently we don't have guaranteed keys/metadata present at the top level - finding the relavant info (payment_id/connector etc) requires context about the lower level functions where this info is extracted - instead this change provides a single log line that is guaranteed to be present for all API calls - And this log line would have all the relevant fields needed for analysis/debugging #
cc7e33a5751d97b44c7aba561c974f529ce8824a
run the application locally all api requests should have the following log line at the end of request - the fields should be populated when available - These log line will be generated even for health & non-existent paths (e.g `/` or `/favicon.ico`) ```json { "message": "[GOLDEN_LOG_LINE - EVENT] REQUEST MIDDLEWARE END", "hostname": "<MY_MACHINE>.local", "pid": 62901, "env": "development", "level": "INFO", "target": "router::middleware", "service": "router", "line": 61, "file": "crates/router/src/middleware.rs", "fn": "golden_log_line", "full_name": "router::middleware::golden_log_line", "time": "2024-01-24T06:35:06.771569000Z", "merchant_id": "merchant_1706060159", "request_id": "018d3a2d-e583-7581-8992-8596b3052995", "extra": { "trace_id": "00000000000000000000000000000000", "http.method": "POST", "http.route": "/payments", "http.flavor": "1.1", "http.user_agent": "PostmanRuntime/7.33.0", "payment_id": "payment_intent_id = \"pay_y8XHx5whOaWTdoGrgAAf\"", "otel.name": "HTTP POST /payments", "http.client_ip": "::1", "http.host": "localhost:8080", "http.target": "/payments", "http.scheme": "http", "otel.kind": "server" } } ```
[ "crates/drainer/src/query.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payments/tokenization.rs", "crates/router/src/lib.rs", "crates/router/src/middleware.rs", "crates/router/src/routes/admin.rs", "crates/router/src/routes/mandates.rs", "crates/router/src/routes/pay...
juspay/hyperswitch
juspay__hyperswitch-3428
Bug: Error: IncompleteMessage: connection closed before message completed ### Bug Description Intermittently few api calls gets closed with the following error `Error: IncompleteMessage: connection closed before message completed`. ### Expected Behavior The application should either kept the connection alive or retry connection. ### Actual Behavior The application is closing the connection and failing the API call Detailed hyper create issue: https://github.com/hyperium/hyper/issues/2136 ### Steps To Reproduce Let the application receive more load. For me, for every 1000 transactions, received one failure with this error. ### Context For The Bug Not able to talk to connector[basically it can be any outgoing call]. ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System : Linux ubuntu 2. Rust version (output of `rustc --version`): `rustc 1.74.0` 3. App version (output of `cargo r --features vergen -- --version`): `router 2024.01.08.0-75-gae83f28-ae83f28-2024-01-23T09:47:32.000000000Z` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 6c3293dba9d..a6d588bd43a 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -106,6 +106,7 @@ counter_metric!(APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT, GLOBAL_METER); counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT, GLOBAL_METER); // Metrics for Auto Retries +counter_metric!(AUTO_RETRY_CONNECTION_CLOSED, GLOBAL_METER); counter_metric!(AUTO_RETRY_ELIGIBLE_REQUEST_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_MISS_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_GSM_FETCH_FAILURE_COUNT, GLOBAL_METER); diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 307dff55071..cf231895892 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -552,8 +552,7 @@ pub async fn send_request( key: consts::METRICS_HOST_TAG_NAME.into(), value: url.host_str().unwrap_or_default().to_string().into(), }; - - let send_request = async { + let request = { match request.method { Method::Get => client.get(url), Method::Post => { @@ -607,32 +606,92 @@ pub async fn send_request( .timeout(Duration::from_secs( option_timeout_secs.unwrap_or(crate::consts::REQUEST_TIME_OUT), )) - .send() - .await - .map_err(|error| match error { - error if error.is_timeout() => { - metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); - errors::ApiClientError::RequestTimeoutReceived - } - error if is_connection_closed(&error) => { - metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); - errors::ApiClientError::ConnectionClosed - } - _ => errors::ApiClientError::RequestNotSent(error.to_string()), - }) - .into_report() - .attach_printable("Unable to send request to connector") }; - metrics_request::record_operation_time( + // We cannot clone the request type, because it has Form trait which is not clonable. So we are cloning the request builder here. + let cloned_send_request = request.try_clone().map(|cloned_request| async { + cloned_request + .send() + .await + .map_err(|error| match error { + error if error.is_timeout() => { + metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); + errors::ApiClientError::RequestTimeoutReceived + } + error if is_connection_closed_before_message_could_complete(&error) => { + metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); + errors::ApiClientError::ConnectionClosedIncompleteMessage + } + _ => errors::ApiClientError::RequestNotSent(error.to_string()), + }) + .into_report() + .attach_printable("Unable to send request to connector") + }); + + let send_request = async { + request + .send() + .await + .map_err(|error| match error { + error if error.is_timeout() => { + metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); + errors::ApiClientError::RequestTimeoutReceived + } + error if is_connection_closed_before_message_could_complete(&error) => { + metrics::REQUEST_BUILD_FAILURE.add(&metrics::CONTEXT, 1, &[]); + errors::ApiClientError::ConnectionClosedIncompleteMessage + } + _ => errors::ApiClientError::RequestNotSent(error.to_string()), + }) + .into_report() + .attach_printable("Unable to send request to connector") + }; + + let response = metrics_request::record_operation_time( send_request, &metrics::EXTERNAL_REQUEST_TIME, - &[metrics_tag], + &[metrics_tag.clone()], ) - .await + .await; + // Retry once if the response is connection closed. + // + // This is just due to the racy nature of networking. + // hyper has a connection pool of idle connections, and it selected one to send your request. + // Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool. + // But occasionally, a connection will be selected from the pool + // and written to at the same time the server is deciding to close the connection. + // Since hyper already wrote some of the request, + // it can’t really retry it automatically on a new connection, since the server may have acted already + match response { + Ok(response) => Ok(response), + Err(error) + if error.current_context() + == &errors::ApiClientError::ConnectionClosedIncompleteMessage => + { + metrics::AUTO_RETRY_CONNECTION_CLOSED.add(&metrics::CONTEXT, 1, &[]); + match cloned_send_request { + Some(cloned_request) => { + logger::info!( + "Retrying request due to connection closed before message could complete" + ); + metrics_request::record_operation_time( + cloned_request, + &metrics::EXTERNAL_REQUEST_TIME, + &[metrics_tag], + ) + .await + } + None => { + logger::info!("Retrying request due to connection closed before message could complete failed as request is not clonable"); + Err(error) + } + } + } + err @ Err(_) => err, + } } -fn is_connection_closed(error: &reqwest::Error) -> bool { +fn is_connection_closed_before_message_could_complete(error: &reqwest::Error) -> bool { let mut source = error.source(); while let Some(err) = source { if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() { @@ -1674,7 +1733,7 @@ pub fn build_redirection_form( // Initialize the ThreeDSService const threeDS = gateway.get3DSecure(); - + const options = {{ customerVaultId: '{customer_vault_id}', currency: '{currency}', diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index ac3a04e85b2..46808a175c3 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -267,7 +267,7 @@ pub enum ApiClientError { RequestTimeoutReceived, #[error("connection closed before a message could complete")] - ConnectionClosed, + ConnectionClosedIncompleteMessage, #[error("Server responded with Internal Server Error")] InternalServerErrorReceived, @@ -285,8 +285,8 @@ impl ApiClientError { pub fn is_upstream_timeout(&self) -> bool { self == &Self::RequestTimeoutReceived } - pub fn is_connection_closed(&self) -> bool { - self == &Self::ConnectionClosed + pub fn is_connection_closed_before_message_could_complete(&self) -> bool { + self == &Self::ConnectionClosedIncompleteMessage } }
2024-01-23T09:45:40Z
## Description Hyper crate has a bug which allows few calls to connect with a dead connections and fails to send request to the server. This bug of hyper can be tracked with below link. `Error: IncompleteMessage: connection closed before message completed` - [Link](https://github.com/hyperium/hyper/issues/2136) Temporary fix: Retry connection with the server by sending the request again when call fails with this issue. Permanent fix would be, whenever reqwest crate release a stable version with hyper's 1.0 version [Another Link](https://epi052.github.io/feroxbuster-docs/docs/faq/connection-closed/) This is just due to the racy nature of networking. hyper has a connection pool of idle connections, and it selected one to send your request. Most of the time, hyper will receive the server’s FIN and drop the dead connection from its pool. But occasionally, a connection will be selected from the pool and written to at the same time the server is deciding to close the connection. Since hyper already wrote some of the request, it can’t really retry it automatically on a new connection, since the server may have acted already ## Motivation and Context Few external api calls fails due to this connection close #
3fbffdc242dafe7983c542573b7c6362f99331e6
Running the test case collections
[ "crates/router/src/routes/metrics.rs", "crates/router/src/services/api.rs", "crates/storage_impl/src/errors.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3423
Bug: Audit trail - Add dispute and refund ID to connector calls
diff --git a/crates/analytics/docs/clickhouse/scripts/connector_events.sql b/crates/analytics/docs/clickhouse/scripts/connector_events.sql index 5821cd03556..4a53f9edb0b 100644 --- a/crates/analytics/docs/clickhouse/scripts/connector_events.sql +++ b/crates/analytics/docs/clickhouse/scripts/connector_events.sql @@ -10,7 +10,9 @@ CREATE TABLE connector_events_queue ( `status_code` UInt32, `created_at` DateTime64(3), `latency` UInt128, - `method` LowCardinality(String) + `method` LowCardinality(String), + `refund_id` Nullable(String), + `dispute_id` Nullable(String) ) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-connector-api-events', kafka_group_name = 'hyper-c1', @@ -32,6 +34,8 @@ CREATE TABLE connector_events_dist ( `inserted_at` DateTime64(3), `latency` UInt128, `method` LowCardinality(String), + `refund_id` Nullable(String), + `dispute_id` Nullable(String), INDEX flowIndex flowTYPE bloom_filter GRANULARITY 1, INDEX connectorIndex connector_name TYPE bloom_filter GRANULARITY 1, INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 @@ -54,7 +58,9 @@ CREATE MATERIALIZED VIEW connector_events_mv TO connector_events_dist ( `status_code` UInt32, `created_at` DateTime64(3), `latency` UInt128, - `method` LowCardinality(String) + `method` LowCardinality(String), + `refund_id` Nullable(String), + `dispute_id` Nullable(String) ) AS SELECT merchant_id, @@ -70,6 +76,8 @@ SELECT now() as inserted_at, latency, method, + refund_id, + dispute_id FROM connector_events_queue where length(_error) = 0; diff --git a/crates/analytics/src/connector_events/events.rs b/crates/analytics/src/connector_events/events.rs index 096520777ee..47044811a8b 100644 --- a/crates/analytics/src/connector_events/events.rs +++ b/crates/analytics/src/connector_events/events.rs @@ -1,7 +1,4 @@ -use api_models::analytics::{ - connector_events::{ConnectorEventsRequest, QueryType}, - Granularity, -}; +use api_models::analytics::{connector_events::ConnectorEventsRequest, Granularity}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -32,11 +29,23 @@ where query_builder .add_filter_clause("merchant_id", merchant_id) .switch()?; - match query_param.query_param { - QueryType::Payment { payment_id } => query_builder - .add_filter_clause("payment_id", payment_id) - .switch()?, + + query_builder + .add_filter_clause("payment_id", query_param.payment_id) + .switch()?; + + if let Some(refund_id) = query_param.refund_id { + query_builder + .add_filter_clause("refund_id", &refund_id) + .switch()?; + } + + if let Some(dispute_id) = query_param.dispute_id { + query_builder + .add_filter_clause("dispute_id", &dispute_id) + .switch()?; } + //TODO!: update the execute_query function to return reports instead of plain errors... query_builder .execute_query::<ConnectorEventsResult, _>(pool) diff --git a/crates/api_models/src/analytics/connector_events.rs b/crates/api_models/src/analytics/connector_events.rs index b2974b0a339..7d7e4ae2a8b 100644 --- a/crates/api_models/src/analytics/connector_events.rs +++ b/crates/api_models/src/analytics/connector_events.rs @@ -1,11 +1,6 @@ -#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] -#[serde(tag = "type")] -pub enum QueryType { - Payment { payment_id: String }, -} - #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ConnectorEventsRequest { - #[serde(flatten)] - pub query_param: QueryType, + pub payment_id: String, + pub refund_id: Option<String>, + pub dispute_id: Option<String>, } diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs index 7f8993af527..8b3eed45f9e 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -119,6 +119,8 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC connector_api_version: None, apple_pay_flow: None, frm_metadata: self.frm_metadata.clone(), + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs index 79b6811a6e9..706a0f9142e 100644 --- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs +++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs @@ -106,6 +106,8 @@ pub async fn construct_fulfillment_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) } diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs index bd0ba3e4f7f..2de6aaab7c7 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -97,6 +97,8 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh connector_api_version: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs index 9c2708b28b3..dfe70570047 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -93,6 +93,8 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp connector_api_version: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs index 5eaa17d3298..a84d9a771b4 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -109,6 +109,8 @@ impl connector_api_version: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs index 25267db1a96..4863edd6fcb 100644 --- a/crates/router/src/core/mandate/utils.rs +++ b/crates/router/src/core/mandate/utils.rs @@ -70,6 +70,8 @@ pub async fn construct_mandate_revoke_router_data( payout_method_data: None, #[cfg(feature = "payouts")] quote_id: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 520582eb22f..fe4a7757ecc 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2997,6 +2997,8 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( external_latency: router_data.external_latency, apple_pay_flow: router_data.apple_pay_flow, frm_metadata: router_data.frm_metadata, + refund_id: router_data.refund_id, + dispute_id: router_data.dispute_id, } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 61917fdcd2e..1c1b11c47b1 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -167,6 +167,8 @@ where external_latency: None, apple_pay_flow, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 016d5ec955d..ef8dddde955 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -176,6 +176,8 @@ pub async fn construct_payout_router_data<'a, F>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) @@ -328,6 +330,8 @@ pub async fn construct_refund_router_data<'a, F>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: Some(refund.refund_id.clone()), + dispute_id: None, }; Ok(router_data) @@ -558,6 +562,8 @@ pub async fn construct_accept_dispute_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + dispute_id: Some(dispute.dispute_id.clone()), + refund_id: None, }; Ok(router_data) } @@ -646,6 +652,8 @@ pub async fn construct_submit_evidence_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: Some(dispute.dispute_id.clone()), }; Ok(router_data) } @@ -740,6 +748,8 @@ pub async fn construct_upload_file_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) } @@ -831,6 +841,8 @@ pub async fn construct_defend_dispute_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: Some(dispute.dispute_id.clone()), }; Ok(router_data) } @@ -915,6 +927,8 @@ pub async fn construct_retrieve_file_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) } diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index 08b49048043..75d37f94279 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -114,6 +114,8 @@ pub async fn construct_webhook_router_data<'a>( external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, }; Ok(router_data) } diff --git a/crates/router/src/events/connector_api_logs.rs b/crates/router/src/events/connector_api_logs.rs index 45c05a3077f..4d3aadc3c45 100644 --- a/crates/router/src/events/connector_api_logs.rs +++ b/crates/router/src/events/connector_api_logs.rs @@ -18,6 +18,8 @@ pub struct ConnectorEvent { created_at: i128, request_id: String, latency: u128, + refund_id: Option<String>, + dispute_id: Option<String>, status_code: u16, } @@ -34,6 +36,8 @@ impl ConnectorEvent { merchant_id: String, request_id: Option<&RequestId>, latency: u128, + refund_id: Option<String>, + dispute_id: Option<String>, status_code: u16, ) -> Self { Self { @@ -54,6 +58,8 @@ impl ConnectorEvent { .map(|i| i.as_hyphenated().to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), latency, + refund_id, + dispute_id, status_code, } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index e0c6a086257..cd672405d24 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -400,6 +400,8 @@ where req.merchant_id.clone(), state.request_id.as_ref(), external_latency, + req.refund_id.clone(), + req.dispute_id.clone(), status_code, ); diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 0809ca17820..741a233ae9f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -319,6 +319,9 @@ pub struct RouterData<Flow, Request, Response> { pub apple_pay_flow: Option<storage_enums::ApplePayFlow>, pub frm_metadata: Option<serde_json::Value>, + + pub dispute_id: Option<String>, + pub refund_id: Option<String>, } #[derive(Debug, Clone, serde::Deserialize)] @@ -1466,6 +1469,8 @@ impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)> external_latency: data.external_latency, apple_pay_flow: data.apple_pay_flow.clone(), frm_metadata: data.frm_metadata.clone(), + dispute_id: data.dispute_id.clone(), + refund_id: data.refund_id.clone(), } } } @@ -1522,6 +1527,8 @@ impl<F1, F2> external_latency: data.external_latency, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index fbd94230584..c03f492e8b8 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -103,6 +103,8 @@ impl VerifyConnectorData { external_latency: None, apple_pay_flow: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index c820b7acd6e..d3f8147fb26 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -98,6 +98,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { apple_pay_flow: None, external_latency: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } } @@ -157,6 +159,8 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { apple_pay_flow: None, external_latency: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index ed3cdbe31b5..844777e2dca 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -524,6 +524,8 @@ pub trait ConnectorActions: Connector { apple_pay_flow: None, external_latency: None, frm_metadata: None, + refund_id: None, + dispute_id: None, } }
2024-01-23T08:03:02Z
added refund_id, dispute_id to connector events ## Description <!-- Describe your changes in detail --> ## Motivation and Context added refund_id, dispute_id for audit trail #
b2afdc35465426bd11428d8d4ac743617a443128
created payment -> created refund for the payment -> checked ConnectorApiLogs for the refund_id
[ "crates/analytics/docs/clickhouse/scripts/connector_events.sql", "crates/analytics/src/connector_events/events.rs", "crates/api_models/src/analytics/connector_events.rs", "crates/router/src/core/fraud_check/flows/checkout_flow.rs", "crates/router/src/core/fraud_check/flows/fulfillment_flow.rs", "crates/ro...
juspay/hyperswitch
juspay__hyperswitch-3432
Bug: feat: Make invite support email array Invite api should support invite of multiple users at a time, instead of single email, it should take an array of emails and sent invitation to each. In case of invitation fails for an email, proper error message should be should be thrown for that email response. Response of multiple invite email will be an array containing email, and the other fields as per success or failure for the response.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 8de6a3c0b4f..056d1b593dc 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -89,6 +89,16 @@ pub struct InviteUserResponse { pub password: Option<Secret<String>>, } +#[derive(Debug, serde::Serialize)] +pub struct InviteMultipleUserResponse { + pub email: pii::Email, + pub is_email_sent: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub password: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option<String>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchMerchantIdRequest { pub merchant_id: String, diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index f4000755b3e..389cb10d7b5 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -56,6 +56,8 @@ pub enum UserErrors { ChangePasswordError, #[error("InvalidDeleteOperation")] InvalidDeleteOperation, + #[error("MaxInvitationsError")] + MaxInvitationsError, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -64,107 +66,118 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon let sub_code = "UR"; match self { Self::InternalServerError => { - AER::InternalServerError(ApiError::new("HE", 0, "Something Went Wrong", None)) + AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None)) + } + Self::InvalidCredentials => { + AER::Unauthorized(ApiError::new(sub_code, 1, self.get_error_message(), None)) + } + Self::UserNotFound => { + AER::Unauthorized(ApiError::new(sub_code, 2, self.get_error_message(), None)) + } + Self::UserExists => { + AER::BadRequest(ApiError::new(sub_code, 3, self.get_error_message(), None)) } - Self::InvalidCredentials => AER::Unauthorized(ApiError::new( - sub_code, - 1, - "Incorrect email or password", - None, - )), - Self::UserNotFound => AER::Unauthorized(ApiError::new( - sub_code, - 2, - "Email doesn’t exist. Register", - None, - )), - Self::UserExists => AER::BadRequest(ApiError::new( - sub_code, - 3, - "An account already exists with this email", - None, - )), Self::LinkInvalid => { - AER::Unauthorized(ApiError::new(sub_code, 4, "Invalid or expired link", None)) + AER::Unauthorized(ApiError::new(sub_code, 4, self.get_error_message(), None)) + } + Self::UnverifiedUser => { + AER::Unauthorized(ApiError::new(sub_code, 5, self.get_error_message(), None)) + } + Self::InvalidOldPassword => { + AER::BadRequest(ApiError::new(sub_code, 6, self.get_error_message(), None)) } - Self::UnverifiedUser => AER::Unauthorized(ApiError::new( - sub_code, - 5, - "Kindly verify your account", - None, - )), - Self::InvalidOldPassword => AER::BadRequest(ApiError::new( - sub_code, - 6, - "Old password incorrect. Please enter the correct password", - None, - )), Self::EmailParsingError => { - AER::BadRequest(ApiError::new(sub_code, 7, "Invalid Email", None)) + AER::BadRequest(ApiError::new(sub_code, 7, self.get_error_message(), None)) } Self::NameParsingError => { - AER::BadRequest(ApiError::new(sub_code, 8, "Invalid Name", None)) + AER::BadRequest(ApiError::new(sub_code, 8, self.get_error_message(), None)) } Self::PasswordParsingError => { - AER::BadRequest(ApiError::new(sub_code, 9, "Invalid Password", None)) + AER::BadRequest(ApiError::new(sub_code, 9, self.get_error_message(), None)) } Self::UserAlreadyVerified => { - AER::Unauthorized(ApiError::new(sub_code, 11, "User already verified", None)) + AER::Unauthorized(ApiError::new(sub_code, 11, self.get_error_message(), None)) } Self::CompanyNameParsingError => { - AER::BadRequest(ApiError::new(sub_code, 14, "Invalid Company Name", None)) + AER::BadRequest(ApiError::new(sub_code, 14, self.get_error_message(), None)) } Self::MerchantAccountCreationError(error_message) => { AER::InternalServerError(ApiError::new(sub_code, 15, error_message, None)) } Self::InvalidEmailError => { - AER::BadRequest(ApiError::new(sub_code, 16, "Invalid Email", None)) + AER::BadRequest(ApiError::new(sub_code, 16, self.get_error_message(), None)) } Self::MerchantIdNotFound => { - AER::BadRequest(ApiError::new(sub_code, 18, "Invalid Merchant ID", None)) + AER::BadRequest(ApiError::new(sub_code, 18, self.get_error_message(), None)) } Self::MetadataAlreadySet => { - AER::BadRequest(ApiError::new(sub_code, 19, "Metadata already set", None)) + AER::BadRequest(ApiError::new(sub_code, 19, self.get_error_message(), None)) } Self::DuplicateOrganizationId => AER::InternalServerError(ApiError::new( sub_code, 21, - "An Organization with the id already exists", + self.get_error_message(), None, )), Self::InvalidRoleId => { - AER::BadRequest(ApiError::new(sub_code, 22, "Invalid Role ID", None)) + AER::BadRequest(ApiError::new(sub_code, 22, self.get_error_message(), None)) } - Self::InvalidRoleOperation => AER::BadRequest(ApiError::new( - sub_code, - 23, - "User Role Operation Not Supported", - None, - )), - Self::IpAddressParsingFailed => { - AER::InternalServerError(ApiError::new(sub_code, 24, "Something Went Wrong", None)) + Self::InvalidRoleOperation => { + AER::BadRequest(ApiError::new(sub_code, 23, self.get_error_message(), None)) } - Self::InvalidMetadataRequest => AER::BadRequest(ApiError::new( + Self::IpAddressParsingFailed => AER::InternalServerError(ApiError::new( sub_code, - 26, - "Invalid Metadata Request", + 24, + self.get_error_message(), None, )), + Self::InvalidMetadataRequest => { + AER::BadRequest(ApiError::new(sub_code, 26, self.get_error_message(), None)) + } Self::MerchantIdParsingError => { - AER::BadRequest(ApiError::new(sub_code, 28, "Invalid Merchant Id", None)) + AER::BadRequest(ApiError::new(sub_code, 28, self.get_error_message(), None)) } - Self::ChangePasswordError => AER::BadRequest(ApiError::new( - sub_code, - 29, - "Old and new password cannot be same", - None, - )), - Self::InvalidDeleteOperation => AER::BadRequest(ApiError::new( - sub_code, - 30, - "Delete Operation Not Supported", - None, - )), + Self::ChangePasswordError => { + AER::BadRequest(ApiError::new(sub_code, 29, self.get_error_message(), None)) + } + Self::InvalidDeleteOperation => { + AER::BadRequest(ApiError::new(sub_code, 30, self.get_error_message(), None)) + } + Self::MaxInvitationsError => { + AER::BadRequest(ApiError::new(sub_code, 31, self.get_error_message(), None)) + } + } + } +} + +impl UserErrors { + pub fn get_error_message(&self) -> &str { + match self { + Self::InternalServerError => "Something went wrong", + Self::InvalidCredentials => "Incorrect email or password", + Self::UserNotFound => "Email doesn’t exist. Register", + Self::UserExists => "An account already exists with this email", + Self::LinkInvalid => "Invalid or expired link", + Self::UnverifiedUser => "Kindly verify your account", + Self::InvalidOldPassword => "Old password incorrect. Please enter the correct password", + Self::EmailParsingError => "Invalid Email", + Self::NameParsingError => "Invalid Name", + Self::PasswordParsingError => "Invalid Password", + Self::UserAlreadyVerified => "User already verified", + Self::CompanyNameParsingError => "Invalid Company Name", + Self::MerchantAccountCreationError(error_message) => error_message, + Self::InvalidEmailError => "Invalid Email", + Self::MerchantIdNotFound => "Invalid Merchant ID", + Self::MetadataAlreadySet => "Metadata already set", + Self::DuplicateOrganizationId => "An Organization with the id already exists", + Self::InvalidRoleId => "Invalid Role ID", + Self::InvalidRoleOperation => "User Role Operation Not Supported", + Self::IpAddressParsingFailed => "Something went wrong", + Self::InvalidMetadataRequest => "Invalid Metadata Request", + Self::MerchantIdParsingError => "Invalid Merchant Id", + Self::ChangePasswordError => "Old and new password cannot be the same", + Self::InvalidDeleteOperation => "Delete Operation Not Supported", + Self::MaxInvitationsError => "Maximum invite count per request exceeded", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 3384e229009..c2ed78f8665 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1,4 +1,4 @@ -use api_models::user as user_api; +use api_models::user::{self as user_api, InviteMultipleUserResponse}; use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew}; #[cfg(feature = "email")] use error_stack::IntoReport; @@ -9,7 +9,7 @@ use router_env::env; #[cfg(feature = "email")] use router_env::logger; -use super::errors::{UserErrors, UserResponse}; +use super::errors::{UserErrors, UserResponse, UserResult}; #[cfg(feature = "email")] use crate::services::email::types as email_types; use crate::{ @@ -407,6 +407,12 @@ pub async fn invite_user( .await .change_context(UserErrors::InternalServerError)?; + let invitation_status = if cfg!(feature = "email") { + UserStatus::InvitationSent + } else { + UserStatus::Active + }; + let now = common_utils::date_time::now(); state .store @@ -415,7 +421,7 @@ pub async fn invite_user( merchant_id: user_from_token.merchant_id, role_id: request.role_id, org_id: user_from_token.org_id, - status: UserStatus::InvitationSent, + status: invitation_status, created_by: user_from_token.user_id.clone(), last_modified_by: user_from_token.user_id, created_at: now, @@ -467,6 +473,181 @@ pub async fn invite_user( } } +pub async fn invite_multiple_user( + state: AppState, + user_from_token: auth::UserFromToken, + requests: Vec<user_api::InviteUserRequest>, +) -> UserResponse<Vec<InviteMultipleUserResponse>> { + if requests.len() > 10 { + return Err(UserErrors::MaxInvitationsError.into()) + .attach_printable("Number of invite requests must not exceed 10"); + } + + let responses = futures::future::join_all(requests.iter().map(|request| async { + match handle_invitation(&state, &user_from_token, request).await { + Ok(response) => response, + Err(error) => InviteMultipleUserResponse { + email: request.email.clone(), + is_email_sent: false, + password: None, + error: Some(error.current_context().get_error_message().to_string()), + }, + } + })) + .await; + + Ok(ApplicationResponse::Json(responses)) +} + +async fn handle_invitation( + state: &AppState, + user_from_token: &auth::UserFromToken, + request: &user_api::InviteUserRequest, +) -> UserResult<InviteMultipleUserResponse> { + let inviter_user = user_from_token.get_user(state.clone()).await?; + + if inviter_user.email == request.email { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("User Inviting themself"); + } + + utils::user_role::validate_role_id(request.role_id.as_str())?; + let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; + let invitee_user = state + .store + .find_user_by_email(invitee_email.clone().get_secret().expose().as_str()) + .await; + + if let Ok(invitee_user) = invitee_user { + handle_existing_user_invitation(state, user_from_token, request, invitee_user.into()).await + } else if invitee_user + .as_ref() + .map_err(|e| e.current_context().is_db_not_found()) + .err() + .unwrap_or(false) + { + handle_new_user_invitation(state, user_from_token, request).await + } else { + Err(UserErrors::InternalServerError.into()) + } +} + +//TODO: send email +async fn handle_existing_user_invitation( + state: &AppState, + user_from_token: &auth::UserFromToken, + request: &user_api::InviteUserRequest, + invitee_user_from_db: domain::UserFromStorage, +) -> UserResult<InviteMultipleUserResponse> { + let now = common_utils::date_time::now(); + state + .store + .insert_user_role(UserRoleNew { + user_id: invitee_user_from_db.get_user_id().to_owned(), + merchant_id: user_from_token.merchant_id.clone(), + role_id: request.role_id.clone(), + org_id: user_from_token.org_id.clone(), + status: UserStatus::Active, + created_by: user_from_token.user_id.clone(), + last_modified_by: user_from_token.user_id.clone(), + created_at: now, + last_modified: now, + }) + .await + .map_err(|e| { + if e.current_context().is_db_unique_violation() { + e.change_context(UserErrors::UserExists) + } else { + e.change_context(UserErrors::InternalServerError) + } + })?; + + Ok(InviteMultipleUserResponse { + email: request.email.clone(), + is_email_sent: false, + password: None, + error: None, + }) +} + +async fn handle_new_user_invitation( + state: &AppState, + user_from_token: &auth::UserFromToken, + request: &user_api::InviteUserRequest, +) -> UserResult<InviteMultipleUserResponse> { + let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?; + + new_user + .insert_user_in_db(state.store.as_ref()) + .await + .change_context(UserErrors::InternalServerError)?; + + let invitation_status = if cfg!(feature = "email") { + UserStatus::InvitationSent + } else { + UserStatus::Active + }; + + let now = common_utils::date_time::now(); + state + .store + .insert_user_role(UserRoleNew { + user_id: new_user.get_user_id().to_owned(), + merchant_id: user_from_token.merchant_id.clone(), + role_id: request.role_id.clone(), + org_id: user_from_token.org_id.clone(), + status: invitation_status, + created_by: user_from_token.user_id.clone(), + last_modified_by: user_from_token.user_id.clone(), + created_at: now, + last_modified: now, + }) + .await + .map_err(|e| { + if e.current_context().is_db_unique_violation() { + e.change_context(UserErrors::UserExists) + } else { + e.change_context(UserErrors::InternalServerError) + } + })?; + + let is_email_sent; + #[cfg(feature = "email")] + { + let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; + let email_contents = email_types::InviteUser { + recipient_email: invitee_email, + user_name: domain::UserName::new(new_user.get_name())?, + settings: state.conf.clone(), + subject: "You have been invited to join Hyperswitch Community!", + }; + let send_email_result = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await; + logger::info!(?send_email_result); + is_email_sent = send_email_result.is_ok(); + } + #[cfg(not(feature = "email"))] + { + is_email_sent = false; + } + + Ok(InviteMultipleUserResponse { + is_email_sent, + password: if cfg!(not(feature = "email")) { + Some(new_user.get_password().get_secret()) + } else { + None + }, + email: request.email.clone(), + error: None, + }) +} + pub async fn create_internal_user( state: AppState, request: user_api::CreateInternalUserRequest, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 71c79295c73..44822efddc4 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -970,6 +970,9 @@ impl User { .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service(web::resource("/user/invite/accept").route(web::post().to(accept_invitation))) .service(web::resource("/update").route(web::post().to(update_user_account_details))) + .service( + web::resource("/user/invite_multiple").route(web::post().to(invite_multiple_user)), + ) .service( web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 30348513c2b..6df8c7fb7a7 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -176,6 +176,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ForgotPassword | Flow::ResetPassword | Flow::InviteUser + | Flow::InviteMultipleUser | Flow::DeleteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmail diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index eca32318adf..02704cf701f 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -350,6 +350,23 @@ pub async fn invite_user( )) .await } +pub async fn invite_multiple_user( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<Vec<user_api::InviteUserRequest>>, +) -> HttpResponse { + let flow = Flow::InviteMultipleUser; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload.into_inner(), + user_core::invite_multiple_user, + &auth::JWTAuth(Permission::UsersWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} #[cfg(feature = "email")] pub async fn verify_email( diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 84f2e3e1267..998c52f2c13 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -321,6 +321,8 @@ pub enum Flow { ResetPassword, /// Invite users InviteUser, + /// Invite multiple users + InviteMultipleUser, /// Delete user DeleteUser, /// Incremental Authorization flow
2024-01-22T23:16:47Z
## Description The endpoint `/invite_multiple`, gives support to invite more than one user at a time. ## Motivation and Context Currently we can only invite one user at a time. #
d827c9af29b8516f379e648e00f4ab307ae1a34d
Curl for invite_multiple: ``` curl --location 'http://localhost:8080/user/user/invite_multiple' \ --header 'Authorization: Bearer JWT' \ --data-raw '[ { "email": "admin7@juspay.in", "name": "25", "role_id": "merchant_view_only" }, { "email": "test2@juspay.in", "name": "25", "role_id": "merchant_view_only" }, { "email": "12345@juspay.n", "name": "25", "role_id": "merchant_view_only" } ]' ``` <img width="1263" alt="Screenshot 2024-01-23 at 4 28 32 AM" src="https://github.com/juspay/hyperswitch/assets/64925866/217cbc2d-a065-4be9-8f04-f3121b017a34">
[ "crates/api_models/src/user.rs", "crates/router/src/core/errors/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "crates/router_env/src/logger/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3421
Bug: feat: signin and verify email changes for invite flow
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 40d082d1cad..04aabc071ae 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -12,9 +12,9 @@ use crate::user::{ }, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, InviteUserRequest, - InviteUserResponse, ResetPasswordRequest, SendVerifyEmailRequest, SignUpRequest, - SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, - UserMerchantCreate, VerifyEmailRequest, + InviteUserResponse, ResetPasswordRequest, SendVerifyEmailRequest, SignInResponse, + SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, + UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -56,6 +56,7 @@ common_utils::impl_misc_api_event_type!( InviteUserResponse, VerifyEmailRequest, SendVerifyEmailRequest, + SignInResponse, UpdateUserAccountDetailsRequest ); diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 056d1b593dc..89f42f58c39 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -39,7 +39,21 @@ pub struct DashboardEntryResponse { pub type SignInRequest = SignUpRequest; -pub type SignInResponse = DashboardEntryResponse; +#[derive(Debug, serde::Serialize)] +#[serde(tag = "flow_type", rename_all = "snake_case")] +pub enum SignInResponse { + MerchantSelect(MerchantSelectResponse), + DashboardEntry(DashboardEntryResponse), +} + +#[derive(Debug, serde::Serialize)] +pub struct MerchantSelectResponse { + pub token: Secret<String>, + pub name: Secret<String>, + pub email: pii::Email, + pub verification_days_left: Option<i64>, + pub merchants: Vec<UserMerchantAccount>, +} #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct ConnectAccountRequest { @@ -138,7 +152,7 @@ pub struct VerifyEmailRequest { pub token: Secret<String>, } -pub type VerifyEmailResponse = DashboardEntryResponse; +pub type VerifyEmailResponse = SignInResponse; #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct SendVerifyEmailRequest { @@ -149,6 +163,7 @@ pub struct SendVerifyEmailRequest { pub struct UserMerchantAccount { pub merchant_id: String, pub merchant_name: OptionalEncryptableName, + pub is_active: bool, } #[cfg(feature = "recon")] diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 389cb10d7b5..d3b1679378e 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -58,6 +58,8 @@ pub enum UserErrors { InvalidDeleteOperation, #[error("MaxInvitationsError")] MaxInvitationsError, + #[error("RoleNotFound")] + RoleNotFound, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -146,6 +148,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::MaxInvitationsError => { AER::BadRequest(ApiError::new(sub_code, 31, self.get_error_message(), None)) } + Self::RoleNotFound => { + AER::BadRequest(ApiError::new(sub_code, 32, self.get_error_message(), None)) + } } } } @@ -178,6 +183,7 @@ impl UserErrors { Self::ChangePasswordError => "Old and new password cannot be the same", Self::InvalidDeleteOperation => "Delete Operation Not Supported", Self::MaxInvitationsError => "Maximum invite count per request exceeded", + Self::RoleNotFound => "Role Not Found", } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c2ed78f8665..ae66728e140 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -97,10 +97,10 @@ pub async fn signup( )) } -pub async fn signin( +pub async fn signin_without_invite_checks( state: AppState, request: user_api::SignInRequest, -) -> UserResponse<user_api::SignInResponse> { +) -> UserResponse<user_api::DashboardEntryResponse> { let user_from_db: domain::UserFromStorage = state .store .find_user_by_email(request.email.clone().expose().expose().as_str()) @@ -124,6 +124,50 @@ pub async fn signin( )) } +pub async fn signin( + state: AppState, + request: user_api::SignInRequest, +) -> UserResponse<user_api::SignInResponse> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_email(request.email.clone().expose().expose().as_str()) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::InvalidCredentials) + } else { + e.change_context(UserErrors::InternalServerError) + } + })? + .into(); + + user_from_db.compare_password(request.password)?; + + let signin_strategy = + if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() { + let preferred_role = user_from_db + .get_role_from_db_by_merchant_id(&state, preferred_merchant_id.as_str()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("User role with preferred_merchant_id not found")?; + domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy { + user: user_from_db, + user_role: preferred_role, + }) + } else { + let user_roles = user_from_db.get_roles_from_db(&state).await?; + domain::SignInWithRoleStrategyType::decide_signin_strategy_by_user_roles( + user_from_db, + user_roles, + ) + .await? + }; + + Ok(ApplicationResponse::Json( + signin_strategy.get_signin_response(&state).await?, + )) +} + #[cfg(feature = "email")] pub async fn connect_account( state: AppState, @@ -832,22 +876,22 @@ pub async fn list_merchant_ids_for_user( state: AppState, user: auth::UserFromToken, ) -> UserResponse<Vec<user_api::UserMerchantAccount>> { - let merchant_ids = utils::user_role::get_merchant_ids_for_user(&state, &user.user_id).await?; + let user_roles = + utils::user_role::get_active_user_roles_for_user(&state, &user.user_id).await?; let merchant_accounts = state .store - .list_multiple_merchant_accounts(merchant_ids) + .list_multiple_merchant_accounts( + user_roles + .iter() + .map(|role| role.merchant_id.clone()) + .collect(), + ) .await .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json( - merchant_accounts - .into_iter() - .map(|acc| user_api::UserMerchantAccount { - merchant_id: acc.merchant_id, - merchant_name: acc.merchant_name, - }) - .collect(), + utils::user::get_multiple_merchant_details_with_status(user_roles, merchant_accounts)?, )) } @@ -868,11 +912,38 @@ pub async fn get_users_for_merchant_account( Ok(ApplicationResponse::Json(user_api::GetUsersResponse(users))) } +#[cfg(feature = "email")] +pub async fn verify_email_without_invite_checks( + state: AppState, + req: user_api::VerifyEmailRequest, +) -> UserResponse<user_api::DashboardEntryResponse> { + let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state) + .await + .change_context(UserErrors::LinkInvalid)?; + let user = state + .store + .find_user_by_email(token.get_email()) + .await + .change_context(UserErrors::InternalServerError)?; + let user = state + .store + .update_user_by_user_id(user.user_id.as_str(), storage_user::UserUpdate::VerifyUser) + .await + .change_context(UserErrors::InternalServerError)?; + let user_from_db: domain::UserFromStorage = user.into(); + let user_role = user_from_db.get_role_from_db(state.clone()).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + + Ok(ApplicationResponse::Json( + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, + )) +} + #[cfg(feature = "email")] pub async fn verify_email( state: AppState, req: user_api::VerifyEmailRequest, -) -> UserResponse<user_api::VerifyEmailResponse> { +) -> UserResponse<user_api::SignInResponse> { let token = auth::decode_jwt::<email_types::EmailToken>(&req.token.clone().expose(), &state) .await .change_context(UserErrors::LinkInvalid)?; @@ -890,11 +961,29 @@ pub async fn verify_email( .change_context(UserErrors::InternalServerError)?; let user_from_db: domain::UserFromStorage = user.into(); - let user_role = user_from_db.get_role_from_db(state.clone()).await?; - let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + + let signin_strategy = + if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() { + let preferred_role = user_from_db + .get_role_from_db_by_merchant_id(&state, preferred_merchant_id.as_str()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("User role with preferred_merchant_id not found")?; + domain::SignInWithRoleStrategyType::SingleRole(domain::SignInWithSingleRoleStrategy { + user: user_from_db, + user_role: preferred_role, + }) + } else { + let user_roles = user_from_db.get_roles_from_db(&state).await?; + domain::SignInWithRoleStrategyType::decide_signin_strategy_by_user_roles( + user_from_db, + user_roles, + ) + .await? + }; Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, + signin_strategy.get_signin_response(&state).await?, )) } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 44822efddc4..7acb23c40ee 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -952,7 +952,10 @@ impl User { let mut route = web::scope("/user").app_data(web::Data::new(state)); route = route - .service(web::resource("/signin").route(web::post().to(user_signin))) + .service( + web::resource("/signin").route(web::post().to(user_signin_without_invite_checks)), + ) + .service(web::resource("/v2/signin").route(web::post().to(user_signin))) .service(web::resource("/change_password").route(web::post().to(change_password))) .service(web::resource("/internal_signup").route(web::post().to(internal_user_signup))) .service(web::resource("/switch_merchant").route(web::post().to(switch_merchant_id))) @@ -961,14 +964,7 @@ impl User { .route(web::post().to(user_merchant_account_create)), ) .service(web::resource("/switch/list").route(web::get().to(list_merchant_ids_for_user))) - .service(web::resource("/user/list").route(web::get().to(get_user_details))) .service(web::resource("/permission_info").route(web::get().to(get_authorization_info))) - .service(web::resource("/user/update_role").route(web::post().to(update_user_role))) - .service(web::resource("/role/list").route(web::get().to(list_roles))) - .service(web::resource("/role").route(web::get().to(get_role_from_token))) - .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) - .service(web::resource("/user/invite").route(web::post().to(invite_user))) - .service(web::resource("/user/invite/accept").route(web::post().to(accept_invitation))) .service(web::resource("/update").route(web::post().to(update_user_account_details))) .service( web::resource("/user/invite_multiple").route(web::post().to(invite_multiple_user)), @@ -980,6 +976,23 @@ impl User { ) .service(web::resource("/user/delete").route(web::delete().to(delete_user_role))); + // User management + route = route.service( + web::scope("/user") + .service(web::resource("/list").route(web::get().to(get_user_details))) + .service(web::resource("/invite").route(web::post().to(invite_user))) + .service(web::resource("/invite/accept").route(web::post().to(accept_invitation))) + .service(web::resource("/update_role").route(web::post().to(update_user_role))), + ); + + // Role information + route = route.service( + web::scope("/role") + .service(web::resource("").route(web::get().to(get_role_from_token))) + .service(web::resource("/list").route(web::get().to(list_all_roles))) + .service(web::resource("/{role_id}").route(web::get().to(get_role))), + ); + #[cfg(feature = "dummy_connector")] { route = route.service( @@ -1000,7 +1013,11 @@ impl User { web::resource("/signup_with_merchant_id") .route(web::post().to(user_signup_with_merchant_id)), ) - .service(web::resource("/verify_email").route(web::post().to(verify_email))) + .service( + web::resource("/verify_email") + .route(web::post().to(verify_email_without_invite_checks)), + ) + .service(web::resource("/v2/verify_email").route(web::post().to(verify_email))) .service( web::resource("/verify_email_request") .route(web::post().to(verify_email_request)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 6df8c7fb7a7..07894afe732 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -161,6 +161,7 @@ impl From<Flow> for ApiIdentifier { Flow::UserConnectAccount | Flow::UserSignUp + | Flow::UserSignInWithoutInviteChecks | Flow::UserSignIn | Flow::ChangePassword | Flow::SetDashboardMetadata @@ -179,6 +180,7 @@ impl From<Flow> for ApiIdentifier { | Flow::InviteMultipleUser | Flow::DeleteUser | Flow::UserSignUpWithMerchantId + | Flow::VerifyEmailWithoutInviteChecks | Flow::VerifyEmail | Flow::VerifyEmailRequest | Flow::UpdateUserAccountDetails => Self::User, diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 02704cf701f..88e19ddf755 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -58,6 +58,25 @@ pub async fn user_signup( .await } +pub async fn user_signin_without_invite_checks( + state: web::Data<AppState>, + http_req: HttpRequest, + json_payload: web::Json<user_api::SignInRequest>, +) -> HttpResponse { + let flow = Flow::UserSignInWithoutInviteChecks; + let req_payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow.clone(), + state, + &http_req, + req_payload.clone(), + |state, _, req_body| user_core::signin_without_invite_checks(state, req_body), + &auth::NoAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn user_signin( state: web::Data<AppState>, http_req: HttpRequest, @@ -368,6 +387,25 @@ pub async fn invite_multiple_user( .await } +#[cfg(feature = "email")] +pub async fn verify_email_without_invite_checks( + state: web::Data<AppState>, + http_req: HttpRequest, + json_payload: web::Json<user_api::VerifyEmailRequest>, +) -> HttpResponse { + let flow = Flow::VerifyEmailWithoutInviteChecks; + Box::pin(api::server_wrap( + flow.clone(), + state, + &http_req, + json_payload.into_inner(), + |state, _, req_payload| user_core::verify_email_without_invite_checks(state, req_payload), + &auth::NoAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "email")] pub async fn verify_email( state: web::Data<AppState>, diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index f83134e5825..3f9ccda8651 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -29,7 +29,7 @@ pub async fn get_authorization_info( .await } -pub async fn list_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { +pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { let flow = Flow::ListRoles; Box::pin(api::server_wrap( flow, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index bbe21f289aa..d3ea69ecd86 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -26,11 +26,12 @@ use crate::{ db::StorageInterface, routes::AppState, services::{ + authentication as auth, authentication::UserFromToken, authorization::{info, predefined_permissions}, }, types::transformers::ForeignFrom, - utils::user::password, + utils::{self, user::password}, }; pub mod dashboard_metadata; @@ -733,7 +734,15 @@ impl UserFromStorage { pub async fn get_role_from_db(&self, state: AppState) -> UserResult<UserRole> { state .store - .find_user_role_by_user_id(self.get_user_id()) + .find_user_role_by_user_id(&self.0.user_id) + .await + .change_context(UserErrors::InternalServerError) + } + + pub async fn get_roles_from_db(&self, state: &AppState) -> UserResult<Vec<UserRole>> { + state + .store + .list_user_roles_by_user_id(&self.0.user_id) .await .change_context(UserErrors::InternalServerError) } @@ -760,6 +769,29 @@ impl UserFromStorage { let days_left_for_verification = last_date_for_verification - today; Ok(Some(days_left_for_verification.whole_days())) } + + pub fn get_preferred_merchant_id(&self) -> Option<String> { + self.0.preferred_merchant_id.clone() + } + + pub async fn get_role_from_db_by_merchant_id( + &self, + state: &AppState, + merchant_id: &str, + ) -> UserResult<UserRole> { + state + .store + .find_user_role_by_user_id_merchant_id(self.get_user_id(), merchant_id) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + UserErrors::RoleNotFound + } else { + UserErrors::InternalServerError + } + }) + .into_report() + } } impl From<info::ModuleInfo> for user_role_api::ModuleInfo { @@ -828,3 +860,101 @@ impl TryFrom<UserAndRoleJoined> for user_api::UserDetails { }) } } + +pub enum SignInWithRoleStrategyType { + SingleRole(SignInWithSingleRoleStrategy), + MultipleRoles(SignInWithMultipleRolesStrategy), +} + +impl SignInWithRoleStrategyType { + pub async fn decide_signin_strategy_by_user_roles( + user: UserFromStorage, + user_roles: Vec<UserRole>, + ) -> UserResult<Self> { + if user_roles.is_empty() { + return Err(UserErrors::InternalServerError.into()); + } + + if let Some(user_role) = user_roles + .iter() + .find(|role| role.status == UserStatus::Active) + { + Ok(Self::SingleRole(SignInWithSingleRoleStrategy { + user, + user_role: user_role.clone(), + })) + } else { + Ok(Self::MultipleRoles(SignInWithMultipleRolesStrategy { + user, + user_roles, + })) + } + } + + pub async fn get_signin_response( + self, + state: &AppState, + ) -> UserResult<user_api::SignInResponse> { + match self { + Self::SingleRole(strategy) => strategy.get_signin_response(state).await, + Self::MultipleRoles(strategy) => strategy.get_signin_response(state).await, + } + } +} + +pub struct SignInWithSingleRoleStrategy { + pub user: UserFromStorage, + pub user_role: UserRole, +} + +impl SignInWithSingleRoleStrategy { + async fn get_signin_response(self, state: &AppState) -> UserResult<user_api::SignInResponse> { + let token = + utils::user::generate_jwt_auth_token(state, &self.user, &self.user_role).await?; + let dashboard_entry_response = + utils::user::get_dashboard_entry_response(state, self.user, self.user_role, token)?; + Ok(user_api::SignInResponse::DashboardEntry( + dashboard_entry_response, + )) + } +} + +pub struct SignInWithMultipleRolesStrategy { + pub user: UserFromStorage, + pub user_roles: Vec<UserRole>, +} + +impl SignInWithMultipleRolesStrategy { + async fn get_signin_response(self, state: &AppState) -> UserResult<user_api::SignInResponse> { + let merchant_accounts = state + .store + .list_multiple_merchant_accounts( + self.user_roles + .iter() + .map(|role| role.merchant_id.clone()) + .collect(), + ) + .await + .change_context(UserErrors::InternalServerError)?; + + let merchant_details = utils::user::get_multiple_merchant_details_with_status( + self.user_roles, + merchant_accounts, + )?; + + Ok(user_api::SignInResponse::MerchantSelect( + user_api::MerchantSelectResponse { + name: self.user.get_name(), + email: self.user.get_email(), + token: auth::UserAuthToken::new_token( + self.user.get_user_id().to_string(), + &state.conf, + ) + .await? + .into(), + merchants: merchant_details, + verification_days_left: utils::user::get_verification_days_left(state, &self.user)?, + }, + )) + } +} diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index a3f9e7978aa..697d10f772e 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -1,5 +1,7 @@ +use std::collections::HashMap; + use api_models::user as user_api; -use diesel_models::user_role::UserRole; +use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; use masking::Secret; @@ -118,3 +120,29 @@ pub fn get_verification_days_left( #[cfg(not(feature = "email"))] return Ok(None); } + +pub fn get_multiple_merchant_details_with_status( + user_roles: Vec<UserRole>, + merchant_accounts: Vec<MerchantAccount>, +) -> UserResult<Vec<user_api::UserMerchantAccount>> { + let roles: HashMap<_, _> = user_roles + .into_iter() + .map(|user_role| (user_role.merchant_id.clone(), user_role)) + .collect(); + + merchant_accounts + .into_iter() + .map(|merchant| { + let role = roles + .get(merchant.merchant_id.as_str()) + .ok_or(UserErrors::InternalServerError.into()) + .attach_printable("Merchant exists but user role doesn't")?; + + Ok(user_api::UserMerchantAccount { + merchant_id: merchant.merchant_id.clone(), + merchant_name: merchant.merchant_name.clone(), + is_active: role.status == UserStatus::Active, + }) + }) + .collect() +} diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 65ead92ad34..7ca06aeda0d 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,5 +1,5 @@ use api_models::user_role as user_role_api; -use diesel_models::enums::UserStatus; +use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; use crate::{ @@ -17,19 +17,17 @@ pub fn is_internal_role(role_id: &str) -> bool { || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER } -pub async fn get_merchant_ids_for_user(state: &AppState, user_id: &str) -> UserResult<Vec<String>> { +pub async fn get_active_user_roles_for_user( + state: &AppState, + user_id: &str, +) -> UserResult<Vec<UserRole>> { Ok(state .store .list_user_roles_by_user_id(user_id) .await .change_context(UserErrors::InternalServerError)? .into_iter() - .filter_map(|ele| { - if ele.status == UserStatus::Active { - return Some(ele.merchant_id); - } - None - }) + .filter(|ele| ele.status == UserStatus::Active) .collect()) } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 998c52f2c13..0d5710820ee 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -267,6 +267,8 @@ pub enum Flow { UserSignUp, /// User Sign Up UserSignUpWithMerchantId, + /// User Sign In without invite checks + UserSignInWithoutInviteChecks, /// User Sign In UserSignIn, /// User connect account @@ -333,6 +335,8 @@ pub enum Flow { SyncOnboardingStatus, /// Reset tracking id ResetTrackingId, + /// Verify email token without invite checks + VerifyEmailWithoutInviteChecks, /// Verify email Token VerifyEmail, /// Send verify email
2024-01-22T13:11:28Z
## Description <!-- Describe your changes in detail --> This PR adds 2 new APIs 1. `/user/v2/signin` 2. `/user/v2/verify_email` These PRs will have checks as mentioned in the below diagram. ```mermaid flowchart TD A["Connect Account"] -- Email --> B{"User Exists"} B -- No --> C["Create new \n Org \n Merchant \n User \n User Role"] C --> D["Send Verify Email"] D --> E["Verify Email Token"] B -- Yes --> D E --> H{"Is there\n any perferred \nmerchant"} subgraph Checks F -- ==0 --> I{{"Send list of \nmerchants which\n user has access to\n along with an\n intermediate token"}} F -- >=1 --> G[Select the first role with active status] H -- Yes --> M["Send the token \nwith that merchant_id"] H -- No --> F{"How many \n active merchants\n does user have \naccess to"} I -- merchant_ids, \nintermediate_token --> O["Accept Invite"] O --> P["Change status to active"] P --> G G --> M end K["Sign In"] -- Email, Password --> H ``` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> To make the invitation process for users better. #
a59ac7d5b98f27f5fb34206c20ef9c37a07259a3
```curl curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "password" }' ``` or ```curl curl --location 'http://localhost:8080/user/v2/verify_email' \ --header 'Content-Type: application/json' \ --data-raw '{ "token": "email token" }' ``` - Response: - If user has a preferred merchant id or user has a active user role ``` { "flow_type": "dashboard_entry", "token": "JWT with merchant_id, user_id, user_role", "merchant_id": "merchant_id", "name": "user name", "email": "user email", "verification_days_left": null, "user_role": "user role" } ``` - If user has no active user role ``` { "flow_type": "merchant_select", "token": "JWT with only user_id", "merchants": [ { "merchant_id": "merchant_id 1", "company_name": "company_name 1", "is_active": false }, { "merchant_id": "merchant_id 2", "company_name": "company_name 2", "is_active": false } ] } ```
[ "crates/api_models/src/events/user.rs", "crates/api_models/src/user.rs", "crates/router/src/core/errors/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user.rs", "crates/router/src/routes/user_role.rs", ...
juspay/hyperswitch
juspay__hyperswitch-3418
Bug: [FEATURE] Add original authorized amount in router data ### Feature Description Add original authorized amount in router data for recurring mandate payments. This field is required in Cybersource for Discover cards recurring mandate payments. ### Possible Implementation Add fields `original_payment_authorized_amount` and `original_payment_authorized_currency` in struct `RecurringMandatePaymentData`. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 72e3de0bf77..db96ff62f6c 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -442,7 +442,7 @@ pub struct ClientRiskInformationRules { #[serde(rename_all = "camelCase")] pub struct Avs { code: String, - code_raw: String, + code_raw: Option<String>, } impl diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 8beb81d9236..7ef47912744 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -10,7 +10,7 @@ use crate::{ connector::utils::{ self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, - PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RouterData, + PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData, }, consts, core::errors, @@ -47,6 +47,7 @@ impl<T> T, ), ) -> Result<Self, Self::Error> { + // This conversion function is used at different places in the file, if updating this, keep a check for those let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; Ok(Self { amount, @@ -81,11 +82,11 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator { + initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, - }, + }), merchant_intitiated_transaction: None, }), ); @@ -272,14 +273,16 @@ pub enum CybersourceActionsTokenType { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator, + initiator: Option<CybersourcePaymentInitiator>, merchant_intitiated_transaction: Option<MerchantInitiatedTransaction>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantInitiatedTransaction { - reason: String, + reason: Option<String>, + //Required for recurring mandates payment + original_authorized_amount: Option<String>, } #[derive(Debug, Serialize)] @@ -470,35 +473,60 @@ impl From<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>> } impl - From<( + TryFrom<( &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, Option<PaymentSolution>, )> for ProcessingInformation { - fn from( + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( (item, solution): ( &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, Option<PaymentSolution>, ), - ) -> Self { + ) -> Result<Self, Self::Error> { let (action_list, action_token_types, authorization_options) = if item.router_data.request.setup_mandate_details.is_some() { ( Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator { + initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, - }, + }), merchant_intitiated_transaction: None, }), ) + } else if item.router_data.request.connector_mandate_id().is_some() { + let original_amount = item + .router_data + .get_recurring_mandate_payment_data()? + .get_original_payment_amount()?; + let original_currency = item + .router_data + .get_recurring_mandate_payment_data()? + .get_original_payment_currency()?; + ( + None, + None, + Some(CybersourceAuthorizationOptions { + initiator: None, + merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { + reason: None, + original_authorized_amount: Some(utils::get_amount_as_string( + &types::api::CurrencyUnit::Base, + original_amount, + original_currency, + )?), + }), + }), + ) } else { (None, None, None) }; - Self { + Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None @@ -509,7 +537,7 @@ impl authorization_options, capture_options: None, commerce_indicator: String::from("internet"), - } + }) } } @@ -533,11 +561,11 @@ impl Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator { + initiator: Some(CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), credential_stored_on_file: Some(true), stored_credential_used: None, - }, + }), merchant_intitiated_transaction: None, }), ) @@ -680,7 +708,7 @@ impl }, }); - let processing_information = ProcessingInformation::from((item, None)); + let processing_information = ProcessingInformation::try_from((item, None))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item.router_data.request.metadata.clone().map(|metadata| { @@ -792,7 +820,7 @@ impl let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); let processing_information = - ProcessingInformation::from((item, Some(PaymentSolution::ApplePay))); + ProcessingInformation::try_from((item, Some(PaymentSolution::ApplePay)))?; let client_reference_information = ClientReferenceInformation::from(item); let expiration_month = apple_pay_data.get_expiry_month()?; let expiration_year = apple_pay_data.get_four_digit_expiry_year()?; @@ -846,7 +874,7 @@ impl }, }); let processing_information = - ProcessingInformation::from((item, Some(PaymentSolution::GooglePay))); + ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay)))?; let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = item.router_data.request.metadata.clone().map(|metadata| { @@ -893,10 +921,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> build_bill_to(item.router_data.get_billing()?, email)?; let order_information = OrderInformationWithBill::from((item, bill_to)); - let processing_information = ProcessingInformation::from(( - item, - Some(PaymentSolution::ApplePay), - )); + let processing_information = ProcessingInformation::try_from( + (item, Some(PaymentSolution::ApplePay)), + )?; let client_reference_information = ClientReferenceInformation::from(item); let payment_information = PaymentInformation::ApplePayToken( @@ -1008,7 +1035,7 @@ impl String, ), ) -> Result<Self, Self::Error> { - let processing_information = ProcessingInformation::from((item, None)); + let processing_information = ProcessingInformation::try_from((item, None))?; let payment_instrument = CybersoucrePaymentInstrument { id: connector_mandate_id, }; @@ -1159,13 +1186,14 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout action_list: None, action_token_types: None, authorization_options: Some(CybersourceAuthorizationOptions { - initiator: CybersourcePaymentInitiator { + initiator: Some(CybersourcePaymentInitiator { initiator_type: None, credential_stored_on_file: None, stored_credential_used: Some(true), - }, + }), merchant_intitiated_transaction: Some(MerchantInitiatedTransaction { - reason: "5".to_owned(), + reason: Some("5".to_owned()), + original_authorized_amount: None, }), }), commerce_indicator: String::from("internet"), @@ -1339,18 +1367,6 @@ impl From<CybersourceIncrementalAuthorizationStatus> for common_enums::Authoriza } } -impl From<CybersourcePaymentStatus> for enums::RefundStatus { - fn from(item: CybersourcePaymentStatus) -> Self { - match item { - CybersourcePaymentStatus::Succeeded | CybersourcePaymentStatus::Transmitted => { - Self::Success - } - CybersourcePaymentStatus::Failed => Self::Failure, - _ => Self::Pending, - } - } -} - #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum CybersourcePaymentsResponse { @@ -1430,7 +1446,7 @@ pub struct ClientProcessorInformation { #[serde(rename_all = "camelCase")] pub struct Avs { code: String, - code_raw: String, + code_raw: Option<String>, } #[derive(Debug, Clone, Deserialize)] diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 8f028e37a9e..c59fea47612 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -24,7 +24,7 @@ use crate::{ consts, core::{ errors::{self, ApiErrorResponse, CustomResult}, - payments::PaymentData, + payments::{PaymentData, RecurringMandatePaymentData}, }, pii::PeekInterface, types::{ @@ -80,6 +80,7 @@ pub trait RouterData { fn get_customer_id(&self) -> Result<String, Error>; fn get_connector_customer_id(&self) -> Result<String, Error>; fn get_preprocessing_id(&self) -> Result<String, Error>; + fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error>; #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>; #[cfg(feature = "payouts")] @@ -249,6 +250,12 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re .to_owned() .ok_or_else(missing_field_err("preprocessing_id")) } + fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error> { + self.recurring_mandate_payment_data + .to_owned() + .ok_or_else(missing_field_err("recurring_mandate_payment_data")) + } + #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error> { self.payout_method_data @@ -1132,6 +1139,22 @@ impl MandateData for payments::MandateAmountData { } } +pub trait RecurringMandateData { + fn get_original_payment_amount(&self) -> Result<i64, Error>; + fn get_original_payment_currency(&self) -> Result<diesel_models::enums::Currency, Error>; +} + +impl RecurringMandateData for RecurringMandatePaymentData { + fn get_original_payment_amount(&self) -> Result<i64, Error> { + self.original_payment_authorized_amount + .ok_or_else(missing_field_err("original_payment_authorized_amount")) + } + fn get_original_payment_currency(&self) -> Result<diesel_models::enums::Currency, Error> { + self.original_payment_authorized_currency + .ok_or_else(missing_field_err("original_payment_authorized_currency")) + } +} + pub trait MandateReferenceData { fn get_connector_mandate_id(&self) -> Result<String, Error>; } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 043863a98fa..c9e1f6137b7 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2045,6 +2045,8 @@ pub struct IncrementalAuthorizationDetails { #[derive(Debug, Default, Clone)] pub struct RecurringMandatePaymentData { pub payment_method_type: Option<storage_enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe + pub original_payment_authorized_amount: Option<i64>, + pub original_payment_authorized_currency: Option<storage_enums::Currency>, } #[derive(Debug, Default, Clone)] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 213adc79fb0..0cbed255348 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -479,6 +479,27 @@ pub async fn get_token_for_recurring_mandate( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + let original_payment_intent = mandate + .original_payment_id + .as_ref() + .async_map(|payment_id| async { + db.find_payment_intent_by_payment_id_merchant_id( + payment_id, + &mandate.merchant_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound) + .map_err(|err| logger::error!(mandate_original_payment_not_found=?err)) + .ok() + }) + .await + .flatten(); + + let original_payment_authorized_amount = original_payment_intent.clone().map(|pi| pi.amount); + let original_payment_authorized_currency = + original_payment_intent.clone().and_then(|pi| pi.currency); + let customer = req.customer_id.clone().get_required_value("customer_id")?; let payment_method_id = { @@ -540,6 +561,8 @@ pub async fn get_token_for_recurring_mandate( Some(payment_method.payment_method), Some(payments::RecurringMandatePaymentData { payment_method_type, + original_payment_authorized_amount, + original_payment_authorized_currency, }), payment_method.payment_method_type, Some(mandate_connector_details), @@ -550,6 +573,8 @@ pub async fn get_token_for_recurring_mandate( Some(payment_method.payment_method), Some(payments::RecurringMandatePaymentData { payment_method_type, + original_payment_authorized_amount, + original_payment_authorized_currency, }), payment_method.payment_method_type, Some(mandate_connector_details),
2024-01-22T09:35:21Z
## Description <!-- Describe your changes in detail --> Add original authorized amount in router data for recurring mandate payments. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3418 #
629d546aa7c774e86d609abec3b3ab5cf0d100a7
Testing can be done by creating a recurring mandate payment in cybersource and using the following discover cards: 6011111111111117, 6011000991300009 Curls: - Payment Intent Create: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 0, "order_details": null, "currency": "USD", "confirm": false, "capture_method": "automatic", "authentication_type": "no_three_ds", "customer_id": "cut2", "email": "johndoe@gmail.com", "description": "Hello this is description", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "metadata": {}, "setup_future_usage": "off_session" }' ``` - Payments - Confirm: `curl --location 'http://localhost:8080/payments/{payment_id}/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data '{ "setup_future_usage": "off_session", "payment_method": "card", "payment_method_type": "credit", "payment_type": "setup_mandate", "off_session": true, "payment_method_data": { "card": { "card_number": "6011000991300009", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8", "language": "en-GB", "color_depth": 24, "screen_height": 1440, "screen_width": 2560, "time_zone": -330, "java_enabled": true, "java_script_enabled": true, "ip_address": "0.0.0.0" }, "mandate_data": { "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, "mandate_type": { "single_use": { "amount": 68607706, "currency": "USD" } } } }'` - Payments - Create using Mandates `curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 200, "currency": "USD", "confirm": true, "customer_id": "{customer_id}", "email": "johndoe@gmail.com", "name": "John Doe", "phone": "999999999", "capture_method": "automatic", "phone_country_code": "+1", "description": "Its my first payment request", "return_url": "https://google.com", "mandate_id": "{mandate_id}", "off_session":true, "browser_info": { "ip_address":"172.0.0.1" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } } }'`
[ "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cybersource/transformers.rs", "crates/router/src/connector/utils.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3407
Bug: Add API doc in README.md for easy access This will help the users to play through the hyperswitch product
diff --git a/README.md b/README.md index dfa77ebe066..0f5e924589f 100644 --- a/README.md +++ b/README.md @@ -12,13 +12,14 @@ The single API to access payment ecosystems across 130+ countries</div> <a href="#%EF%B8%8F-quick-start-guide">Quick Start Guide</a> • <a href="https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md">Local Setup Guide</a> • <a href="#-fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> • + <a href="https://api-reference.hyperswitch.io/introduction"> API Docs </a> • <a href="#-supported-features">Supported Features</a> • - <a href="#-FAQs">FAQs</a> <br> <a href="#whats-included">What's Included</a> • <a href="#-join-us-in-building-hyperswitch">Join us in building HyperSwitch</a> • <a href="#-community">Community</a> • <a href="#-bugs-and-feature-requests">Bugs and feature requests</a> • + <a href="#-FAQs">FAQs</a> • <a href="#-versioning">Versioning</a> • <a href="#%EF%B8%8F-copyright-and-license">Copyright and License</a> </p>
2024-01-19T10:52:35Z
## Description Add Api Documentation link to the README.md ## Motivation and Context Making Api docs accessible to the users. #
ec16ed0f82f258c5699d54a386f67aff06c0d144
[ "README.md" ]
juspay/hyperswitch
juspay__hyperswitch-3403
Bug: [BUG] [CRYPTOPAY] PSYNC Call Failing ### Bug Description The PSYNC call is failing for connector cryptopay which is resulting in payments getting stuck in the `requires_customer_action` state. ### Expected Behavior The PSYNC should work for connector cryptopay and payments should go into `succeeded`. ### Actual Behavior The PSYNC call is failing for connector cryptopay which is resulting in payments getting stuck in the `requires_customer_action` state. <img width="450" alt="Screenshot 2024-01-19 at 2 55 29 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/ff58a9a5-b062-46f4-be02-1cbcf1d855e0"> <img width="1270" alt="Screenshot 2024-01-19 at 2 55 59 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/46aa4d11-d4f1-453b-bd31-6a61c177c8ba"> ### Steps To Reproduce 1. Create a `crypto_currency` payment for connector `cryptopay`. 2. Try to do PSYNC on the payment. ### Context For The Bug https://juspay.slack.com/archives/C05SDGYKFM1/p1705507357108199 ### Environment ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs index 95ea7ef0c7a..8727461ba34 100644 --- a/crates/router/src/connector/cryptopay.rs +++ b/crates/router/src/connector/cryptopay.rs @@ -69,14 +69,24 @@ where req: &types::RouterData<Flow, Request, Response>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let api_method = self.get_http_method().to_string(); - let body = types::RequestBody::get_inner_value(self.get_request_body(req, connectors)?) - .peek() - .to_owned(); - let md5_payload = crypto::Md5 - .generate_digest(body.as_bytes()) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - let payload = encode(md5_payload); + let method = self.get_http_method(); + let payload = match method { + common_utils::request::Method::Get => String::default(), + common_utils::request::Method::Post + | common_utils::request::Method::Put + | common_utils::request::Method::Delete + | common_utils::request::Method::Patch => { + let body = + types::RequestBody::get_inner_value(self.get_request_body(req, connectors)?) + .peek() + .to_owned(); + let md5_payload = crypto::Md5 + .generate_digest(body.as_bytes()) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + encode(md5_payload) + } + }; + let api_method = method.to_string(); let now = date_time::date_as_yyyymmddthhmmssmmmz() .into_report()
2024-01-19T09:27:21Z
## Description <!-- Describe your changes in detail --> The encoding for empty string in header generation for PSYNC call is removed. This encoding was previously causing the PSYNC call to fail. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3403 #
1c04ac751240f5c931df0f282af1e0ad745e9509
- Create a crypto_currency payment for connector cryptopay. `curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 10, "currency": "INR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "custo", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_experience": "redirect_to_url", "payment_method_data": { "crypto": { "pay_currency": "XRP" } }, "billing": { "address": { "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "test", "quantity": 1, "amount": 10 } ], "business_label": "food", "business_country": "US" }'` - Try to do PSYNC on the payment and status of the payment should be `succeeded` `curl --location 'http://localhost:8080/payments/{payment_id}' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE'`
[ "crates/router/src/connector/cryptopay.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3395
Bug: Clickhouse - split the ingestion & query tables in separate databases for better access control In order to support our earlier use case where we wanna reduce user confusion etc for tables on grafana, we've decided to restrict grafana (and application) access to query tables only. in order to do this we've decided to separate the query & ingestion database names table format - `hyperswitch_<env>_pub` for query tables & `hyperswitch_<env>` for ingestions tables with this format we will be creating new databases with the `_pub` suffix in this case the Kafka & MV tables would reside in the private db while the cluster & audit tables would reside in the public database... as part of this let's also delete the dist tables and query directly from cluster tables since we don't use sharding... in this case we'll rename the clustered tables to remove the clustered suffix e.g `payment_attempt_clustered -> payment_attempt` The following action items need to be taken - [ ] Create new database with _pub suffix - [ ] Create a replica cluster/audit table in the newer public db & backfill it from the older cluster table - [ ] setup an mv from queue to cluster/audit tables - [x] code changes to change the table name (instead of relying on `payment_attempt_dist` we'll rely on `payment_attempt`) - [x] env changes to specify the newer database names - [ ] update access for the users to have access only to their respective env public databases
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index f81c29c801c..00ae3b6e310 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -354,11 +354,11 @@ impl ToSql<ClickhouseClient> for PrimitiveDateTime { impl ToSql<ClickhouseClient> for AnalyticsCollection { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { - Self::Payment => Ok("payment_attempt_dist".to_string()), - Self::Refund => Ok("refund_dist".to_string()), - Self::SdkEvents => Ok("sdk_events_dist".to_string()), - Self::ApiEvents => Ok("api_audit_log".to_string()), - Self::PaymentIntent => Ok("payment_intents_dist".to_string()), + Self::Payment => Ok("payment_attempts".to_string()), + Self::Refund => Ok("refunds".to_string()), + Self::SdkEvents => Ok("sdk_events_audit".to_string()), + Self::ApiEvents => Ok("api_events_audit".to_string()), + Self::PaymentIntent => Ok("payment_intents".to_string()), Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), }
2024-01-18T19:40:01Z
## Description updated analytics tables of ckh source to new tables ## Motivation and Context Segregating tables in ckh for better access control #
cc7e33a5751d97b44c7aba561c974f529ce8824a
- check the analytics tab in dashboard
[ "crates/analytics/src/clickhouse.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3269
Bug: Deep health check for Hyperswitch Drainer Components to be verified in this check - [x] RDS (PostgreSQL) - Connection to Database - State of Migration - [x] ElastiCache (Redis) - Connection to Redis
diff --git a/Cargo.lock b/Cargo.lock index f0334ce9cfc..49ccfc2c645 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2331,6 +2331,7 @@ checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" name = "drainer" version = "0.1.0" dependencies = [ + "actix-web", "async-bb8-diesel", "async-trait", "bb8", @@ -2342,8 +2343,10 @@ dependencies = [ "error-stack", "external_services", "masking", + "mime", "once_cell", "redis_interface", + "reqwest", "router_env", "serde", "serde_json", diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index e4611f43bcf..a8f3db11e39 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -9,6 +9,7 @@ pub struct RouterHealthCheckResponse { } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SchedulerHealthCheckResponse { pub database: bool, diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 67169a15104..0533bd12dab 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -14,13 +14,16 @@ hashicorp-vault = ["external_services/hashicorp-vault"] vergen = ["router_env/vergen"] [dependencies] +actix-web = "4.3.1" async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } bb8 = "0.8" clap = { version = "4.3.2", default-features = false, features = ["std", "derive", "help", "usage"] } config = { version = "0.13.3", features = ["toml"] } diesel = { version = "2.1.0", features = ["postgres"] } error-stack = "0.3.1" +mime = "0.3.17" once_cell = "1.18.0" +reqwest = { version = "0.11.18" } serde = "1.0.193" serde_json = "1.0.108" serde_path_to_error = "0.1.14" diff --git a/crates/drainer/src/errors.rs b/crates/drainer/src/errors.rs index 3034e849f8a..8605ee2ba04 100644 --- a/crates/drainer/src/errors.rs +++ b/crates/drainer/src/errors.rs @@ -15,6 +15,22 @@ pub enum DrainerError { ParsingError(error_stack::Report<common_utils::errors::ParsingError>), #[error("Unexpected error occurred: {0}")] UnexpectedError(String), + #[error("I/O: {0}")] + IoError(std::io::Error), +} + +#[derive(Debug, Error, Clone, serde::Serialize)] +pub enum HealthCheckError { + #[error("Database health check is failing with error: {message}")] + DbError { message: String }, + #[error("Redis health check is failing with error: {message}")] + RedisError { message: String }, +} + +impl From<std::io::Error> for DrainerError { + fn from(err: std::io::Error) -> Self { + Self::IoError(err) + } } pub type DrainerResult<T> = error_stack::Result<T, DrainerError>; @@ -30,3 +46,13 @@ impl From<error_stack::Report<redis::errors::RedisError>> for DrainerError { Self::RedisError(err) } } + +impl actix_web::ResponseError for HealthCheckError { + fn status_code(&self) -> reqwest::StatusCode { + use reqwest::StatusCode; + + match self { + Self::DbError { .. } | Self::RedisError { .. } => StatusCode::INTERNAL_SERVER_ERROR, + } + } +} diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs new file mode 100644 index 00000000000..33b4a1395a8 --- /dev/null +++ b/crates/drainer/src/health_check.rs @@ -0,0 +1,268 @@ +use std::sync::Arc; + +use actix_web::{web, Scope}; +use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; +use common_utils::errors::CustomResult; +use diesel_models::{Config, ConfigNew}; +use error_stack::ResultExt; +use router_env::{instrument, logger, tracing}; + +use crate::{ + connection::{pg_connection, redis_connection}, + errors::HealthCheckError, + services::{self, Store}, + settings::Settings, +}; + +pub const TEST_STREAM_NAME: &str = "TEST_STREAM_0"; +pub const TEST_STREAM_DATA: &[(&str, &str)] = &[("data", "sample_data")]; + +pub struct Health; + +impl Health { + pub fn server(conf: Settings, store: Arc<Store>) -> Scope { + web::scope("health") + .app_data(web::Data::new(conf)) + .app_data(web::Data::new(store)) + .service(web::resource("").route(web::get().to(health))) + .service(web::resource("/ready").route(web::get().to(deep_health_check))) + } +} + +#[instrument(skip_all)] +pub async fn health() -> impl actix_web::Responder { + logger::info!("Drainer health was called"); + actix_web::HttpResponse::Ok().body("Drainer health is good") +} + +#[instrument(skip_all)] +pub async fn deep_health_check( + conf: web::Data<Settings>, + store: web::Data<Arc<Store>>, +) -> impl actix_web::Responder { + match deep_health_check_func(conf, store).await { + Ok(response) => services::http_response_json( + serde_json::to_string(&response) + .map_err(|err| { + logger::error!(serialization_error=?err); + }) + .unwrap_or_default(), + ), + + Err(err) => services::log_and_return_error_response(err), + } +} + +#[instrument(skip_all)] +pub async fn deep_health_check_func( + conf: web::Data<Settings>, + store: web::Data<Arc<Store>>, +) -> Result<DrainerHealthCheckResponse, error_stack::Report<HealthCheckError>> { + logger::info!("Deep health check was called"); + + logger::debug!("Database health check begin"); + + let db_status = store.health_check_db().await.map(|_| true).map_err(|err| { + error_stack::report!(HealthCheckError::DbError { + message: err.to_string() + }) + })?; + + logger::debug!("Database health check end"); + + logger::debug!("Redis health check begin"); + + let redis_status = store + .health_check_redis(&conf.into_inner()) + .await + .map(|_| true) + .map_err(|err| { + error_stack::report!(HealthCheckError::RedisError { + message: err.to_string() + }) + })?; + + logger::debug!("Redis health check end"); + + Ok(DrainerHealthCheckResponse { + database: db_status, + redis: redis_status, + }) +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct DrainerHealthCheckResponse { + pub database: bool, + pub redis: bool, +} + +#[async_trait::async_trait] +pub trait HealthCheckInterface { + async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError>; + async fn health_check_redis(&self, conf: &Settings) -> CustomResult<(), HealthCheckRedisError>; +} + +#[async_trait::async_trait] +impl HealthCheckInterface for Store { + async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError> { + let conn = pg_connection(&self.master_pool).await; + + conn + .transaction_async(|conn| { + Box::pin(async move { + let query = + diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1")); + let _x: i32 = query.get_result_async(&conn).await.map_err(|err| { + logger::error!(read_err=?err,"Error while reading element in the database"); + HealthCheckDBError::DbReadError + })?; + + logger::debug!("Database read was successful"); + + let config = ConfigNew { + key: "test_key".to_string(), + config: "test_value".to_string(), + }; + + config.insert(&conn).await.map_err(|err| { + logger::error!(write_err=?err,"Error while writing to database"); + HealthCheckDBError::DbWriteError + })?; + + logger::debug!("Database write was successful"); + + Config::delete_by_key(&conn, "test_key").await.map_err(|err| { + logger::error!(delete_err=?err,"Error while deleting element in the database"); + HealthCheckDBError::DbDeleteError + })?; + + logger::debug!("Database delete was successful"); + + Ok::<_, HealthCheckDBError>(()) + }) + }) + .await?; + + Ok(()) + } + + async fn health_check_redis(&self, conf: &Settings) -> CustomResult<(), HealthCheckRedisError> { + let redis_conn = redis_connection(conf).await; + + redis_conn + .serialize_and_set_key_with_expiry("test_key", "test_value", 30) + .await + .change_context(HealthCheckRedisError::SetFailed)?; + + logger::debug!("Redis set_key was successful"); + + redis_conn + .get_key("test_key") + .await + .change_context(HealthCheckRedisError::GetFailed)?; + + logger::debug!("Redis get_key was successful"); + + redis_conn + .delete_key("test_key") + .await + .change_context(HealthCheckRedisError::DeleteFailed)?; + + logger::debug!("Redis delete_key was successful"); + + redis_conn + .stream_append_entry( + TEST_STREAM_NAME, + &redis_interface::RedisEntryId::AutoGeneratedID, + TEST_STREAM_DATA.to_vec(), + ) + .await + .change_context(HealthCheckRedisError::StreamAppendFailed)?; + + logger::debug!("Stream append succeeded"); + + let output = self + .redis_conn + .stream_read_entries(TEST_STREAM_NAME, "0-0", Some(10)) + .await + .change_context(HealthCheckRedisError::StreamReadFailed)?; + logger::debug!("Stream read succeeded"); + + let (_, id_to_trim) = output + .get(TEST_STREAM_NAME) + .and_then(|entries| { + entries + .last() + .map(|last_entry| (entries, last_entry.0.clone())) + }) + .ok_or(error_stack::report!( + HealthCheckRedisError::StreamReadFailed + ))?; + logger::debug!("Stream parse succeeded"); + + redis_conn + .stream_trim_entries( + TEST_STREAM_NAME, + ( + redis_interface::StreamCapKind::MinID, + redis_interface::StreamCapTrim::Exact, + id_to_trim, + ), + ) + .await + .change_context(HealthCheckRedisError::StreamTrimFailed)?; + logger::debug!("Stream trim succeeded"); + + Ok(()) + } +} + +#[allow(clippy::enum_variant_names)] +#[derive(Debug, thiserror::Error)] +pub enum HealthCheckDBError { + #[error("Error while connecting to database")] + DbError, + #[error("Error while writing to database")] + DbWriteError, + #[error("Error while reading element in the database")] + DbReadError, + #[error("Error while deleting element in the database")] + DbDeleteError, + #[error("Unpredictable error occurred")] + UnknownError, + #[error("Error in database transaction")] + TransactionError, +} + +impl From<diesel::result::Error> for HealthCheckDBError { + fn from(error: diesel::result::Error) -> Self { + match error { + diesel::result::Error::DatabaseError(_, _) => Self::DbError, + + diesel::result::Error::RollbackErrorOnCommit { .. } + | diesel::result::Error::RollbackTransaction + | diesel::result::Error::AlreadyInTransaction + | diesel::result::Error::NotInTransaction + | diesel::result::Error::BrokenTransactionManager => Self::TransactionError, + + _ => Self::UnknownError, + } + } +} + +#[allow(clippy::enum_variant_names)] +#[derive(Debug, thiserror::Error)] +pub enum HealthCheckRedisError { + #[error("Failed to set key value in Redis")] + SetFailed, + #[error("Failed to get key value in Redis")] + GetFailed, + #[error("Failed to delete key value in Redis")] + DeleteFailed, + #[error("Failed to append data to the stream in Redis")] + StreamAppendFailed, + #[error("Failed to read data from the stream in Redis")] + StreamReadFailed, + #[error("Failed to trim data from the stream in Redis")] + StreamTrimFailed, +} diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index abb32c87796..909ae065e26 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -1,6 +1,7 @@ mod connection; pub mod errors; mod handler; +mod health_check; pub mod logger; pub(crate) mod metrics; mod query; @@ -11,6 +12,7 @@ mod types; mod utils; use std::sync::Arc; +use actix_web::dev::Server; use common_utils::signals::get_allowed_signals; use diesel_models::kv; use error_stack::{IntoReport, ResultExt}; @@ -18,7 +20,10 @@ use router_env::{instrument, tracing}; use tokio::sync::mpsc; use crate::{ - connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData, + connection::pg_connection, + services::Store, + settings::{DrainerSettings, Settings}, + types::StreamData, }; pub async fn start_drainer(store: Arc<Store>, conf: DrainerSettings) -> errors::DrainerResult<()> { @@ -49,3 +54,18 @@ pub async fn start_drainer(store: Arc<Store>, conf: DrainerSettings) -> errors:: Ok(()) } + +pub async fn start_web_server( + conf: Settings, + store: Arc<Store>, +) -> Result<Server, errors::DrainerError> { + let server = conf.server.clone(); + let web_server = actix_web::HttpServer::new(move || { + actix_web::App::new().service(health_check::Health::server(conf.clone(), store.clone())) + }) + .bind((server.host.as_str(), server.port))? + .run(); + let _ = web_server.handle(); + + Ok(web_server) +} diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs index 34c1294d55f..943a66f6791 100644 --- a/crates/drainer/src/main.rs +++ b/crates/drainer/src/main.rs @@ -1,4 +1,7 @@ -use drainer::{errors::DrainerResult, logger::logger, services, settings, start_drainer}; +use drainer::{ + errors::DrainerResult, logger::logger, services, settings, start_drainer, start_web_server, +}; +use router_env::tracing::Instrument; #[tokio::main] async fn main() -> DrainerResult<()> { @@ -24,6 +27,19 @@ async fn main() -> DrainerResult<()> { [router_env::service_name!()], ); + #[allow(clippy::expect_used)] + let web_server = Box::pin(start_web_server(conf.clone(), store.clone())) + .await + .expect("Failed to create the server"); + + tokio::spawn( + async move { + let _ = web_server.await; + logger::error!("The health check probe stopped working!"); + } + .in_current_span(), + ); + logger::debug!(startup_config=?conf); logger::info!("Drainer started [{:?}] [{:?}]", conf.drainer, conf.log); diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index 4393ebb9dc9..0d0b78c0cc6 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -1,6 +1,12 @@ use std::sync::Arc; -use crate::connection::{diesel_make_pg_pool, PgPool}; +use actix_web::{body, HttpResponse, ResponseError}; +use error_stack::Report; + +use crate::{ + connection::{diesel_make_pg_pool, PgPool}, + logger, +}; #[derive(Clone)] pub struct Store { @@ -45,3 +51,23 @@ impl Store { } } } + +pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse +where + T: error_stack::Context + ResponseError + Clone, +{ + logger::error!(?error); + let body = serde_json::json!({ + "message": error.to_string() + }) + .to_string(); + HttpResponse::InternalServerError() + .content_type(mime::APPLICATION_JSON) + .body(body) +} + +pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse { + HttpResponse::Ok() + .content_type(mime::APPLICATION_JSON) + .body(response) +} diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 5b80ee375f5..49cb5f4c7c2 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -30,6 +30,7 @@ pub struct CmdLineConf { #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Settings { + pub server: Server, pub master_database: Database, pub redis: redis::RedisSettings, pub log: Log, @@ -62,6 +63,24 @@ pub struct DrainerSettings { pub loop_interval: u32, // in milliseconds } +#[derive(Debug, Deserialize, Clone)] +#[serde(default)] +pub struct Server { + pub port: u16, + pub workers: usize, + pub host: String, +} + +impl Server { + pub fn validate(&self) -> Result<(), errors::DrainerError> { + common_utils::fp_utils::when(self.host.is_default_or_empty(), || { + Err(errors::DrainerError::ConfigParsingError( + "server host must not be empty".into(), + )) + }) + } +} + impl Default for Database { fn default() -> Self { Self { @@ -88,6 +107,16 @@ impl Default for DrainerSettings { } } +impl Default for Server { + fn default() -> Self { + Self { + host: "127.0.0.1".to_string(), + port: 8080, + workers: 1, + } + } +} + impl Database { fn validate(&self) -> Result<(), errors::DrainerError> { use common_utils::fp_utils::when; @@ -169,6 +198,7 @@ impl Settings { } pub fn validate(&self) -> Result<(), errors::DrainerError> { + self.server.validate()?; self.master_database.validate()?; self.redis.validate().map_err(|error| { println!("{error}");
2024-01-18T18:14:31Z
## Description <!-- Describe your changes in detail --> This PR adds support for performing a deeper health check of the drainer which includes: Database connection check with read, write and delete queries (Added support for database transaction too) Redis connection check with set, get and delete key (Set key with expiry of 30sec) The deep health check API returns a 200 status code if all the components are in good health, but returns 500 if at least one component's health is down ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
892b04f805c219e2cf7cbe5736aef19909e986f7
1. `/health` ![image](https://github.com/juspay/hyperswitch/assets/70657455/d7784ea7-7d21-426f-ba65-69a0f559356e) 2. `/health/deep_check` ![image](https://github.com/juspay/hyperswitch/assets/70657455/aada988f-0058-48af-8654-1070bd810a29) **THIS CANNOT BE TESTED ON SANBOX AS THE ENDPOINT IS NOT EXPOSED**
[ "Cargo.lock", "crates/api_models/src/health_check.rs", "crates/drainer/Cargo.toml", "crates/drainer/src/errors.rs", "crates/drainer/src/health_check.rs", "crates/drainer/src/lib.rs", "crates/drainer/src/main.rs", "crates/drainer/src/services.rs", "crates/drainer/src/settings.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3394
Bug: bug(EVENT_VIEWER): connector events is missing a status code field The status code is being always registered as `0` in clickhouse. ![Image](https://github.com/juspay/hyperswitch/assets/21202349/6c45e608-d976-453d-9594-0312c59abbb9) It seems that we aren't setting the status code at all from the application... we should be able to extract the status code via a simple snippet ```rs let status_code = response .as_ref() .map(|i| i.map_or_else(|value| value.status_code, |value| value.status_code)).unwrap_or_default(); ```
diff --git a/crates/router/src/events/connector_api_logs.rs b/crates/router/src/events/connector_api_logs.rs index 871a7af0d77..45c05a3077f 100644 --- a/crates/router/src/events/connector_api_logs.rs +++ b/crates/router/src/events/connector_api_logs.rs @@ -18,6 +18,7 @@ pub struct ConnectorEvent { created_at: i128, request_id: String, latency: u128, + status_code: u16, } impl ConnectorEvent { @@ -33,6 +34,7 @@ impl ConnectorEvent { merchant_id: String, request_id: Option<&RequestId>, latency: u128, + status_code: u16, ) -> Self { Self { connector_name, @@ -52,6 +54,7 @@ impl ConnectorEvent { .map(|i| i.as_hyphenated().to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), latency, + status_code, } } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 307dff55071..7f69954a8f7 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -372,7 +372,13 @@ where let response = call_connector_api(state, request).await; let external_latency = current_time.elapsed().as_millis(); logger::debug!(connector_response=?response); - + let status_code = response + .as_ref() + .map(|i| { + i.as_ref() + .map_or_else(|value| value.status_code, |value| value.status_code) + }) + .unwrap_or_default(); let connector_event = ConnectorEvent::new( req.connector.clone(), std::any::type_name::<T>(), @@ -394,6 +400,7 @@ where req.merchant_id.clone(), state.request_id.as_ref(), external_latency, + status_code, ); match connector_event.try_into() {
2024-01-18T17:37:58Z
## Description adding status code to connector Kafka events ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
0e4e18441d024b7d669b27d6f8a2feb3eccedb2a
f do payment confirm call and then check for the status_code in log in loki where ```topic=hyperswitch-outgoing-connector-events```
[ "crates/router/src/events/connector_api_logs.rs", "crates/router/src/services/api.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3427
Bug: [BUG] Add payout features for euclid_wasm crate ### Bug Description `euclid_wasm` is a dependency of hyperswitch dashboard which includes list of connectors, PMs, and other related structs and enums. This also includes payout related stuff which is enabled under `payouts` feature. However, the feature `payouts` itself is missing from `euclid_wasm` crate. This needs to be added in the crate. ### Expected Behavior To be able to include payout related definitions in `euclid_wasm` in the final target if the feature was enabled. ### Actual Behavior Payout related definitions are not included in wasm target. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index d9f5330a1b8..13296bcde62 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -10,7 +10,7 @@ rust-version.workspace = true crate-type = ["cdylib"] [features] -default = ["connector_choice_bcompat", "connector_choice_mca_id"] +default = ["connector_choice_bcompat","payouts", "connector_choice_mca_id"] release = ["connector_choice_bcompat", "connector_choice_mca_id"] connector_choice_bcompat = ["api_models/connector_choice_bcompat"] connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connector_choice_mca_id", "kgraph_utils/connector_choice_mca_id"] @@ -18,6 +18,7 @@ dummy_connector = ["kgraph_utils/dummy_connector", "connector_configs/dummy_conn production = ["connector_configs/production"] development = ["connector_configs/development"] sandbox = ["connector_configs/sandbox"] +payouts = [] [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" }
2024-01-18T13:59:39Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
f1fd0b101791f20980e21e8fd8bf10fac3179209
<img width="1675" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/7d08729a-a8b0-46b7-856d-c5587c795649">
[ "crates/euclid_wasm/Cargo.toml" ]
juspay/hyperswitch
juspay__hyperswitch-3386
Bug: feat: get user role from token
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 72fca2b2f08..b057f8ca8bc 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -43,6 +43,7 @@ pub enum Permission { SurchargeDecisionManagerRead, UsersRead, UsersWrite, + MerchantAccountCreate, } #[derive(Debug, serde::Serialize)] @@ -60,6 +61,7 @@ pub enum PermissionModule { Files, ThreeDsDecisionManager, SurchargeDecisionManager, + AccountCreate, } #[derive(Debug, serde::Serialize)] diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 2b7752d1904..d8ff836e1f8 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -20,7 +20,7 @@ pub async fn get_authorization_info( user_role_api::AuthorizationInfoResponse( info::get_authorization_info() .into_iter() - .filter_map(|module| module.try_into().ok()) + .map(Into::into) .collect(), ), )) @@ -63,6 +63,22 @@ pub async fn get_role( Ok(ApplicationResponse::Json(info)) } +pub async fn get_role_from_token( + _state: AppState, + user: auth::UserFromToken, +) -> UserResponse<Vec<user_role_api::Permission>> { + Ok(ApplicationResponse::Json( + predefined_permissions::PREDEFINED_PERMISSIONS + .get(user.role_id.as_str()) + .ok_or(UserErrors::InternalServerError.into()) + .attach_printable("Invalid Role Id in JWT")? + .get_permissions() + .iter() + .map(|&per| per.into()) + .collect(), + )) +} + pub async fn update_user_role( state: AppState, user_from_token: auth::UserFromToken, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0c489dbe63a..34a3b5db51b 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -919,6 +919,7 @@ impl User { .service(web::resource("/permission_info").route(web::get().to(get_authorization_info))) .service(web::resource("/user/update_role").route(web::post().to(update_user_role))) .service(web::resource("/role/list").route(web::get().to(list_roles))) + .service(web::resource("/role").route(web::get().to(get_role_from_token))) .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service( diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 12cf76be475..4dffcb1d38d 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -180,9 +180,11 @@ impl From<Flow> for ApiIdentifier { | Flow::VerifyEmail | Flow::VerifyEmailRequest => Self::User, - Flow::ListRoles | Flow::GetRole | Flow::UpdateUserRole | Flow::GetAuthorizationInfo => { - Self::UserRole - } + Flow::ListRoles + | Flow::GetRole + | Flow::GetRoleFromToken + | Flow::UpdateUserRole + | Flow::GetAuthorizationInfo => Self::UserRole, Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index c96e099ab16..fe305942d03 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -7,7 +7,7 @@ use crate::{ core::{api_locking, user_role as user_role_core}, services::{ api, - authentication::{self as auth}, + authentication::{self as auth, UserFromToken}, authorization::permissions::Permission, }, }; @@ -64,6 +64,20 @@ pub async fn get_role( .await } +pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::GetRoleFromToken; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + (), + |state, user: UserFromToken, _| user_role_core::get_role_from_token(state, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn update_user_role( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index cef93f82739..99e4f1b6c09 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -15,16 +15,13 @@ pub struct PermissionInfo { impl PermissionInfo { pub fn new(permissions: &[Permission]) -> Vec<Self> { - let mut permission_infos = Vec::with_capacity(permissions.len()); - for permission in permissions { - if let Some(description) = Permission::get_permission_description(permission) { - permission_infos.push(Self { - enum_name: permission.clone(), - description, - }) - } - } - permission_infos + permissions + .iter() + .map(|&per| Self { + description: Permission::get_permission_description(&per), + enum_name: per, + }) + .collect() } } @@ -43,6 +40,7 @@ pub enum PermissionModule { Files, ThreeDsDecisionManager, SurchargeDecisionManager, + AccountCreate, } impl PermissionModule { @@ -60,7 +58,8 @@ impl PermissionModule { Self::Disputes => "Everything related to disputes - like creating and viewing dispute related information are within this module", Self::Files => "Permissions for uploading, deleting and viewing files for disputes", Self::ThreeDsDecisionManager => "View and configure 3DS decision rules configured for a merchant", - Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant" + Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant", + Self::AccountCreate => "Create new account within your organization" } } } @@ -173,6 +172,11 @@ impl ModuleInfo { Permission::SurchargeDecisionManagerRead, ]), }, + PermissionModule::AccountCreate => Self { + module: module_name, + description, + permissions: PermissionInfo::new(&[Permission::MerchantAccountCreate]), + }, } } } diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 426b048e88b..5c5e3ecce30 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -1,6 +1,6 @@ use strum::Display; -#[derive(PartialEq, Display, Clone, Debug)] +#[derive(PartialEq, Display, Clone, Debug, Copy)] pub enum Permission { PaymentRead, PaymentWrite, @@ -34,45 +34,43 @@ pub enum Permission { } impl Permission { - pub fn get_permission_description(&self) -> Option<&'static str> { + pub fn get_permission_description(&self) -> &'static str { match self { - Self::PaymentRead => Some("View all payments"), - Self::PaymentWrite => Some("Create payment, download payments data"), - Self::RefundRead => Some("View all refunds"), - Self::RefundWrite => Some("Create refund, download refunds data"), - Self::ApiKeyRead => Some("View API keys (masked generated for the system"), - Self::ApiKeyWrite => Some("Create and update API keys"), - Self::MerchantAccountRead => Some("View merchant account details"), + Self::PaymentRead => "View all payments", + Self::PaymentWrite => "Create payment, download payments data", + Self::RefundRead => "View all refunds", + Self::RefundWrite => "Create refund, download refunds data", + Self::ApiKeyRead => "View API keys (masked generated for the system", + Self::ApiKeyWrite => "Create and update API keys", + Self::MerchantAccountRead => "View merchant account details", Self::MerchantAccountWrite => { - Some("Update merchant account details, configure webhooks, manage api keys") + "Update merchant account details, configure webhooks, manage api keys" } - Self::MerchantConnectorAccountRead => Some("View connectors configured"), + Self::MerchantConnectorAccountRead => "View connectors configured", Self::MerchantConnectorAccountWrite => { - Some("Create, update, verify and delete connector configurations") + "Create, update, verify and delete connector configurations" } - Self::ForexRead => Some("Query Forex data"), - Self::RoutingRead => Some("View routing configuration"), - Self::RoutingWrite => Some("Create and activate routing configurations"), - Self::DisputeRead => Some("View disputes"), - Self::DisputeWrite => Some("Create and update disputes"), - Self::MandateRead => Some("View mandates"), - Self::MandateWrite => Some("Create and update mandates"), - Self::CustomerRead => Some("View customers"), - Self::CustomerWrite => Some("Create, update and delete customers"), - Self::FileRead => Some("View files"), - Self::FileWrite => Some("Create, update and delete files"), - Self::Analytics => Some("Access to analytics module"), - Self::ThreeDsDecisionManagerWrite => Some("Create and update 3DS decision rules"), + Self::ForexRead => "Query Forex data", + Self::RoutingRead => "View routing configuration", + Self::RoutingWrite => "Create and activate routing configurations", + Self::DisputeRead => "View disputes", + Self::DisputeWrite => "Create and update disputes", + Self::MandateRead => "View mandates", + Self::MandateWrite => "Create and update mandates", + Self::CustomerRead => "View customers", + Self::CustomerWrite => "Create, update and delete customers", + Self::FileRead => "View files", + Self::FileWrite => "Create, update and delete files", + Self::Analytics => "Access to analytics module", + Self::ThreeDsDecisionManagerWrite => "Create and update 3DS decision rules", Self::ThreeDsDecisionManagerRead => { - Some("View all 3DS decision rules configured for a merchant") + "View all 3DS decision rules configured for a merchant" } - Self::SurchargeDecisionManagerWrite => { - Some("Create and update the surcharge decision rules") - } - Self::SurchargeDecisionManagerRead => Some("View all the surcharge decision rules"), - Self::UsersRead => Some("View all the users for a merchant"), - Self::UsersWrite => Some("Invite users, assign and update roles"), - Self::MerchantAccountCreate => None, + Self::SurchargeDecisionManagerWrite => "Create and update the surcharge decision rules", + Self::SurchargeDecisionManagerRead => "View all the surcharge decision rules", + Self::UsersRead => "View all the users for a merchant", + Self::UsersWrite => "Invite users, assign and update roles", + Self::MerchantAccountCreate => "Create merchant account", } } } diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index d271ed5e29d..53c88f8aea1 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -762,19 +762,13 @@ impl UserFromStorage { } } -impl TryFrom<info::ModuleInfo> for user_role_api::ModuleInfo { - type Error = (); - fn try_from(value: info::ModuleInfo) -> Result<Self, Self::Error> { - let mut permissions = Vec::with_capacity(value.permissions.len()); - for permission in value.permissions { - let permission = permission.try_into()?; - permissions.push(permission); - } - Ok(Self { +impl From<info::ModuleInfo> for user_role_api::ModuleInfo { + fn from(value: info::ModuleInfo) -> Self { + Self { module: value.module.into(), description: value.description, - permissions, - }) + permissions: value.permissions.into_iter().map(Into::into).collect(), + } } } @@ -794,18 +788,17 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule { info::PermissionModule::Files => Self::Files, info::PermissionModule::ThreeDsDecisionManager => Self::ThreeDsDecisionManager, info::PermissionModule::SurchargeDecisionManager => Self::SurchargeDecisionManager, + info::PermissionModule::AccountCreate => Self::AccountCreate, } } } -impl TryFrom<info::PermissionInfo> for user_role_api::PermissionInfo { - type Error = (); - fn try_from(value: info::PermissionInfo) -> Result<Self, Self::Error> { - let enum_name = (&value.enum_name).try_into()?; - Ok(Self { - enum_name, +impl From<info::PermissionInfo> for user_role_api::PermissionInfo { + fn from(value: info::PermissionInfo) -> Self { + Self { + enum_name: value.enum_name.into(), description: value.description, - }) + } } } diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index c474a82981b..65ead92ad34 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,7 +1,6 @@ use api_models::user_role as user_role_api; use diesel_models::enums::UserStatus; use error_stack::ResultExt; -use router_env::logger; use crate::{ consts, @@ -44,52 +43,50 @@ pub fn validate_role_id(role_id: &str) -> UserResult<()> { pub fn get_role_name_and_permission_response( role_info: &RoleInfo, ) -> Option<(Vec<user_role_api::Permission>, &'static str)> { - role_info - .get_permissions() - .iter() - .map(TryInto::try_into) - .collect::<Result<Vec<user_role_api::Permission>, _>>() - .ok() - .zip(role_info.get_name()) + role_info.get_name().map(|name| { + ( + role_info + .get_permissions() + .iter() + .map(|&per| per.into()) + .collect::<Vec<user_role_api::Permission>>(), + name, + ) + }) } -impl TryFrom<&Permission> for user_role_api::Permission { - type Error = (); - fn try_from(value: &Permission) -> Result<Self, Self::Error> { +impl From<Permission> for user_role_api::Permission { + fn from(value: Permission) -> Self { match value { - Permission::PaymentRead => Ok(Self::PaymentRead), - Permission::PaymentWrite => Ok(Self::PaymentWrite), - Permission::RefundRead => Ok(Self::RefundRead), - Permission::RefundWrite => Ok(Self::RefundWrite), - Permission::ApiKeyRead => Ok(Self::ApiKeyRead), - Permission::ApiKeyWrite => Ok(Self::ApiKeyWrite), - Permission::MerchantAccountRead => Ok(Self::MerchantAccountRead), - Permission::MerchantAccountWrite => Ok(Self::MerchantAccountWrite), - Permission::MerchantConnectorAccountRead => Ok(Self::MerchantConnectorAccountRead), - Permission::MerchantConnectorAccountWrite => Ok(Self::MerchantConnectorAccountWrite), - Permission::ForexRead => Ok(Self::ForexRead), - Permission::RoutingRead => Ok(Self::RoutingRead), - Permission::RoutingWrite => Ok(Self::RoutingWrite), - Permission::DisputeRead => Ok(Self::DisputeRead), - Permission::DisputeWrite => Ok(Self::DisputeWrite), - Permission::MandateRead => Ok(Self::MandateRead), - Permission::MandateWrite => Ok(Self::MandateWrite), - Permission::CustomerRead => Ok(Self::CustomerRead), - Permission::CustomerWrite => Ok(Self::CustomerWrite), - Permission::FileRead => Ok(Self::FileRead), - Permission::FileWrite => Ok(Self::FileWrite), - Permission::Analytics => Ok(Self::Analytics), - Permission::ThreeDsDecisionManagerWrite => Ok(Self::ThreeDsDecisionManagerWrite), - Permission::ThreeDsDecisionManagerRead => Ok(Self::ThreeDsDecisionManagerRead), - Permission::SurchargeDecisionManagerWrite => Ok(Self::SurchargeDecisionManagerWrite), - Permission::SurchargeDecisionManagerRead => Ok(Self::SurchargeDecisionManagerRead), - Permission::UsersRead => Ok(Self::UsersRead), - Permission::UsersWrite => Ok(Self::UsersWrite), - - Permission::MerchantAccountCreate => { - logger::error!("Invalid use of internal permission"); - Err(()) - } + Permission::PaymentRead => Self::PaymentRead, + Permission::PaymentWrite => Self::PaymentWrite, + Permission::RefundRead => Self::RefundRead, + Permission::RefundWrite => Self::RefundWrite, + Permission::ApiKeyRead => Self::ApiKeyRead, + Permission::ApiKeyWrite => Self::ApiKeyWrite, + Permission::MerchantAccountRead => Self::MerchantAccountRead, + Permission::MerchantAccountWrite => Self::MerchantAccountWrite, + Permission::MerchantConnectorAccountRead => Self::MerchantConnectorAccountRead, + Permission::MerchantConnectorAccountWrite => Self::MerchantConnectorAccountWrite, + Permission::ForexRead => Self::ForexRead, + Permission::RoutingRead => Self::RoutingRead, + Permission::RoutingWrite => Self::RoutingWrite, + Permission::DisputeRead => Self::DisputeRead, + Permission::DisputeWrite => Self::DisputeWrite, + Permission::MandateRead => Self::MandateRead, + Permission::MandateWrite => Self::MandateWrite, + Permission::CustomerRead => Self::CustomerRead, + Permission::CustomerWrite => Self::CustomerWrite, + Permission::FileRead => Self::FileRead, + Permission::FileWrite => Self::FileWrite, + Permission::Analytics => Self::Analytics, + Permission::ThreeDsDecisionManagerWrite => Self::ThreeDsDecisionManagerWrite, + Permission::ThreeDsDecisionManagerRead => Self::ThreeDsDecisionManagerRead, + Permission::SurchargeDecisionManagerWrite => Self::SurchargeDecisionManagerWrite, + Permission::SurchargeDecisionManagerRead => Self::SurchargeDecisionManagerRead, + Permission::UsersRead => Self::UsersRead, + Permission::UsersWrite => Self::UsersWrite, + Permission::MerchantAccountCreate => Self::MerchantAccountCreate, } } } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 0d6636e567d..d48aa5f95fe 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -297,6 +297,8 @@ pub enum Flow { ListRoles, /// Get role GetRole, + /// Get role from token + GetRoleFromToken, /// Update user role UpdateUserRole, /// Create merchant account for user in a org
2024-01-18T10:53:30Z
## Description Added API to get list of permission user has. <!-- Describe your changes in detail --> ## Motivation and Context Required for hyperswitch control centre <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
059e86607dc271c25bb3d23f5adfc7d5f21f62fb
``` curl --location --request GET '<URL>/user/role' \ --header 'Authorization: Bearer <JWT>' ``` Above API should give an array of permission. All roles and their permission can be found [here](https://github.com/juspay/hyperswitch/blob/main/crates/router/src/services/authorization/predefined_permissions.rs#L28). Example response, ``` [ "PaymentRead", "RefundRead", "ApiKeyRead", "MerchantAccountRead", "MerchantConnectorAccountRead", "RoutingRead", "ForexRead", "ThreeDsDecisionManagerRead", "SurchargeDecisionManagerRead", "Analytics", "DisputeRead", "MandateRead", "CustomerRead", "FileRead", "UsersRead" ] ```
[ "crates/api_models/src/user_role.rs", "crates/router/src/core/user_role.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user_role.rs", "crates/router/src/services/authorization/info.rs", "crates/router/src/services/authorization/permissions.rs"...
juspay/hyperswitch
juspay__hyperswitch-3379
Bug: [FEATURE] Pass Customer name to connectors ### Feature Description I need customer_name to be passed to stripe. This is required for evaluating the risk associated with a payment. ### Possible Implementation Pass the `name` field ( `customer.name` ) when creating a customer at the connector. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 01ae751f748..596ea1145ec 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -147,7 +147,7 @@ pub struct StaxCustomerRequest { #[serde(skip_serializing_if = "Option::is_none")] email: Option<Email>, #[serde(skip_serializing_if = "Option::is_none")] - firstname: Option<String>, + firstname: Option<Secret<String>>, } impl TryFrom<&types::ConnectorCustomerRouterData> for StaxCustomerRequest { diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 89e18692414..1dbb310868a 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2018,7 +2018,7 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest { description: item.request.description.to_owned(), email: item.request.email.to_owned(), phone: item.request.phone.to_owned(), - name: item.request.name.to_owned().map(Secret::new), + name: item.request.name.to_owned(), source: item.request.preprocessing_id.to_owned(), }) } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 15c79f4b9d9..c6de222f7d8 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -376,7 +376,7 @@ impl<F> TryFrom<&types::RouterData<F, types::PaymentsAuthorizeData, types::Payme payment_method_data: data.request.payment_method_data.clone(), description: None, phone: None, - name: None, + name: data.request.customer_name.clone(), preprocessing_id: data.preprocessing_id.clone(), }) } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5ab6bffc8e6..c7b1ecc2669 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -34,7 +34,7 @@ pub async fn construct_payment_router_data<'a, F, T>( connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, - customer: &Option<domain::Customer>, + customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where @@ -89,6 +89,7 @@ where connector_name: connector_id.to_string(), payment_data: payment_data.clone(), state, + customer_data: customer, }; let customer_id = customer.to_owned().map(|customer| customer.customer_id); @@ -968,6 +969,7 @@ where connector_name: String, payment_data: PaymentData<F>, state: &'a AppState, + customer_data: &'a Option<domain::Customer>, } impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizeData { type Error = error_stack::Report<errors::ApiErrorResponse>; @@ -1048,6 +1050,17 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz .as_ref() .map(|surcharge_details| surcharge_details.final_amount) .unwrap_or(payment_data.amount.into()); + + let customer_name = additional_data + .customer_data + .as_ref() + .and_then(|customer_data| { + customer_data + .name + .as_ref() + .map(|customer| customer.clone().into_inner()) + }); + Ok(Self { payment_method_data: payment_method_data.get_required_value("payment_method_data")?, setup_future_usage: payment_data.payment_intent.setup_future_usage, @@ -1062,6 +1075,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz currency: payment_data.currency, browser_info, email: payment_data.email, + customer_name, payment_experience: payment_data.payment_attempt.payment_experience, order_details, order_category, @@ -1354,6 +1368,17 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; + + let customer_name = additional_data + .customer_data + .as_ref() + .and_then(|customer_data| { + customer_data + .name + .as_ref() + .map(|customer| customer.clone().into_inner()) + }); + Ok(Self { currency: payment_data.currency, confirm: true, @@ -1368,6 +1393,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequ setup_mandate_details: payment_data.setup_mandate, router_return_url, email: payment_data.email, + customer_name, return_url: payment_data.payment_intent.return_url, browser_info, payment_method_type: attempt.payment_method_type, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index e236113e676..0809ca17820 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -392,6 +392,7 @@ pub struct PaymentsAuthorizeData { /// ``` pub amount: i64, pub email: Option<Email>, + pub customer_name: Option<Secret<String>>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, @@ -461,7 +462,7 @@ pub struct ConnectorCustomerData { pub description: Option<String>, pub email: Option<Email>, pub phone: Option<Secret<String>>, - pub name: Option<String>, + pub name: Option<Secret<String>>, pub preprocessing_id: Option<String>, pub payment_method_data: payments::PaymentMethodData, } @@ -586,6 +587,7 @@ pub struct SetupMandateRequestData { pub router_return_url: Option<String>, pub browser_info: Option<BrowserInformation>, pub email: Option<Email>, + pub customer_name: Option<Secret<String>>, pub return_url: Option<String>, pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub request_incremental_authorization: bool, @@ -1342,19 +1344,6 @@ impl From<&&mut PaymentsAuthorizeRouterData> for AuthorizeSessionTokenData { } } -impl From<&&mut PaymentsAuthorizeRouterData> for ConnectorCustomerData { - fn from(data: &&mut PaymentsAuthorizeRouterData) -> Self { - Self { - email: data.request.email.to_owned(), - preprocessing_id: data.preprocessing_id.to_owned(), - payment_method_data: data.request.payment_method_data.to_owned(), - description: None, - phone: None, - name: None, - } - } -} - impl<F> From<&RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>> for PaymentMethodTokenizationData { @@ -1411,6 +1400,7 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData { setup_mandate_details: data.request.setup_mandate_details.clone(), router_return_url: data.request.router_return_url.clone(), email: data.request.email.clone(), + customer_name: data.request.customer_name.clone(), amount: 0, statement_descriptor: None, capture_method: None, diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index c5fcce8b185..fbd94230584 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -24,6 +24,7 @@ impl VerifyConnectorData { types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(self.card_details.clone()), email: None, + customer_name: None, amount: 1000, confirm: true, currency: storage_enums::Currency::USD, diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 35c9cbd952d..c820b7acd6e 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -59,6 +59,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { order_details: None, order_category: None, email: None, + customer_name: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 49075080506..430ae0bac14 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -147,6 +147,7 @@ impl AdyenTest { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index 8bac7c13c85..892d5b1f208 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -81,6 +81,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 68c4eb94bf3..9d082445719 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -57,6 +57,7 @@ impl CashtocodeTest { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type, session_token: None, diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index 73ee93178c0..9a476df7fe6 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -83,6 +83,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index 5df8d80461f..5e1b3f5ab47 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -81,6 +81,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index b140a7c0517..69edec2af2c 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -82,6 +82,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { order_details: None, order_category: None, email: None, + customer_name: None, payment_experience: None, payment_method_type: None, session_token: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index db82cd7e032..ed3cdbe31b5 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -900,6 +900,7 @@ impl Default for PaymentAuthorizeType { order_details: None, order_category: None, email: None, + customer_name: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 4f7a94780a5..8b865789003 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -92,6 +92,7 @@ impl WorldlineTest { order_details: None, order_category: None, email: None, + customer_name: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None,
2024-01-18T08:58:20Z
## Description <!-- Describe your changes in detail --> This PR adds the support for sending `customer_name` to the connectors when creating the customer at the connectors end. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Passing customer name to the connector might be required for metadata scanning to evaluate the payment score and risk associated with a payment. #
6c46e9c19b304bb11f304e60c46e8abf67accf6d
- Create a payment for stripe connector with customer id, email and customer name. ```bash curl --location 'https://sandbox.hyperswitch.io/payments' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_16svHskpygTeiHAoy6RsRf3YxKlSV67FhT5P49UvfA73P1sTG1Tm6VG58a2B79Il' \ --data-raw '{ "amount": 696969, "currency": "USD", "confirm": true, "name": "John Cena", "capture_method": "automatic", "phone": "999999999", "phone_country_code": "+65", "customer_id": "new_stripe_customer_7", "email": "example@juspay.in", "description": "Its my first payment request", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "key1":"hello" } }' ``` - Check the customer name at stripe dashboard. <img width="507" alt="image" src="https://github.com/juspay/hyperswitch/assets/48803246/9df093e0-a66b-41ce-82c0-1b5567d7b4e2">
[ "crates/router/src/connector/stax/transformers.rs", "crates/router/src/connector/stripe/transformers.rs", "crates/router/src/core/payments/flows/authorize_flow.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/types.rs", "crates/router/src/types/api/verify_connector.rs", "crates...
juspay/hyperswitch
juspay__hyperswitch-3375
Bug: [CI] Add workflow to ensure a pull request contains at least one linked issue ### Description Add a CI workflow to ensure that each pull request contains at least one linked issue. We wish to introduce this requirement for improved project tracking. The workflow should do nothing else: just succeed/fail the check based on the presence/absence of linked issues in a pull request, respectively.
2024-01-17T20:12:40Z
## Description <!-- Describe your changes in detail --> This PR adds a new pull request CI check to ensure that all pull requests have at least one linked issue. However, GitHub does not send any webhooks when a pull request is linked with an issue, so the check does not get triggered automatically when an issue is linked for a pull request which is already open. One way to trigger it manually is to update either the pull request title or description/body, and another is to push commits. Since pushing new commits tends to trigger all other checks, editing the pull request description might be preferable in such scenarios. In addition, the PR includes the following changes: - Renames the `conventional-commit-check.yml` workflow file to `pr-convention-checks.yml`. - Removes the workflow code that labelled pull requests whose titles didn't follow conventional commit standards, since we no longer use the label for any purpose nowadays. It was initially added as a means to filter pull requests by that label, when we introduced the check. The pull request can be reviewed one commit at a time for better understanding. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #3375. #
eb2a61d8597995838f21b8233653c691118b2191
Temporarily modified the trigger to be `pull_request` instead of `pull_request_target` to test the workflow. 1. The check fails if the PR does not contain any linked issues. ![Screenshot of failed check due to absence of linked issues](https://github.com/juspay/hyperswitch/assets/22217505/a8f5a7ac-d96f-4512-ae6d-caf7ae1c0b5c) Link to check run: https://github.com/juspay/hyperswitch/actions/runs/7561263548/job/20589130650?pr=3376 2. The check succeeds if the PR contains at least one linked issue. ![Screenshot of successful check run](https://github.com/juspay/hyperswitch/assets/22217505/779214c3-4552-463d-8dbd-34f8a403c41f) Link to check run: https://github.com/juspay/hyperswitch/actions/runs/7561509816/job/20589902417?pr=3376 3. The check fails if any of the linked issues is closed. ![Screenshot of failed check run due to one of the issues being closed](https://github.com/juspay/hyperswitch/assets/22217505/2b4b1b44-8978-4cf4-96c6-54c23a223380)
[]
juspay/hyperswitch
juspay__hyperswitch-3390
Bug: feat: delete / deactivate user Add endpoint to support a delete user. A user who is part of the organisation can be deleted by users with permission `UsersWrite`, provided user to be deleted should not be the org admin or internal user.
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index c8d8fd96a7a..3ec30d6bd97 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -1,8 +1,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ - AcceptInvitationRequest, AuthorizationInfoResponse, GetRoleRequest, ListRolesResponse, - RoleInfoResponse, UpdateUserRoleRequest, + AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, GetRoleRequest, + ListRolesResponse, RoleInfoResponse, UpdateUserRoleRequest, }; common_utils::impl_misc_api_event_type!( @@ -11,5 +11,6 @@ common_utils::impl_misc_api_event_type!( GetRoleRequest, AuthorizationInfoResponse, UpdateUserRoleRequest, - AcceptInvitationRequest + AcceptInvitationRequest, + DeleteUserRoleRequest ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index d2548935f62..e8c9b777c7f 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,3 +1,5 @@ +use common_utils::pii; + use crate::user::DashboardEntryResponse; #[derive(Debug, serde::Serialize)] @@ -101,3 +103,8 @@ pub struct AcceptInvitationRequest { } pub type AcceptInvitationResponse = DashboardEntryResponse; + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct DeleteUserRoleRequest { + pub email: pii::Email, +} diff --git a/crates/diesel_models/src/query/dashboard_metadata.rs b/crates/diesel_models/src/query/dashboard_metadata.rs index 678bcc2fd1f..b1cb034eb1f 100644 --- a/crates/diesel_models/src/query/dashboard_metadata.rs +++ b/crates/diesel_models/src/query/dashboard_metadata.rs @@ -104,4 +104,18 @@ impl DashboardMetadata { ) .await } + + pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + conn: &PgPooledConn, + user_id: String, + merchant_id: String, + ) -> StorageResult<bool> { + generics::generic_delete::<<Self as HasTable>::Table, _>( + conn, + dsl::user_id + .eq(user_id) + .and(dsl::merchant_id.eq(merchant_id)), + ) + .await + } } diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index 6b408038ef5..e67eba64c7c 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -54,9 +54,18 @@ impl UserRole { .await } - pub async fn delete_by_user_id(conn: &PgPooledConn, user_id: String) -> StorageResult<bool> { - generics::generic_delete::<<Self as HasTable>::Table, _>(conn, dsl::user_id.eq(user_id)) - .await + pub async fn delete_by_user_id_merchant_id( + conn: &PgPooledConn, + user_id: String, + merchant_id: String, + ) -> StorageResult<bool> { + generics::generic_delete::<<Self as HasTable>::Table, _>( + conn, + dsl::user_id + .eq(user_id) + .and(dsl::merchant_id.eq(merchant_id)), + ) + .await } pub async fn list_by_user_id(conn: &PgPooledConn, user_id: String) -> StorageResult<Vec<Self>> { diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 330e02cd547..f4000755b3e 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -54,6 +54,8 @@ pub enum UserErrors { MerchantIdParsingError, #[error("ChangePasswordError")] ChangePasswordError, + #[error("InvalidDeleteOperation")] + InvalidDeleteOperation, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -157,6 +159,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon "Old and new password cannot be same", None, )), + Self::InvalidDeleteOperation => AER::BadRequest(ApiError::new( + sub_code, + 30, + "Delete Operation Not Supported", + None, + )), } } } diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 245f8d246d2..742c281b89a 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -1,6 +1,7 @@ use api_models::user_role as user_role_api; use diesel_models::{enums::UserStatus, user_role::UserRoleUpdate}; use error_stack::ResultExt; +use masking::ExposeInterface; use router_env::logger; use crate::{ @@ -11,6 +12,7 @@ use crate::{ authorization::{info, predefined_permissions}, ApplicationResponse, }, + types::domain, utils, }; @@ -161,3 +163,88 @@ pub async fn accept_invitation( Ok(ApplicationResponse::StatusOk) } + +pub async fn delete_user_role( + state: AppState, + user_from_token: auth::UserFromToken, + request: user_role_api::DeleteUserRoleRequest, +) -> UserResponse<()> { + let user_from_db: domain::UserFromStorage = state + .store + .find_user_by_email( + domain::UserEmail::from_pii_email(request.email)? + .get_secret() + .expose() + .as_str(), + ) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::InvalidRoleOperation) + .attach_printable("User not found in records") + } else { + e.change_context(UserErrors::InternalServerError) + } + })? + .into(); + + if user_from_db.get_user_id() == user_from_token.user_id { + return Err(UserErrors::InvalidDeleteOperation.into()) + .attach_printable("User deleting himself"); + } + + let user_roles = state + .store + .list_user_roles_by_user_id(user_from_db.get_user_id()) + .await + .change_context(UserErrors::InternalServerError)?; + + match user_roles + .iter() + .find(|&role| role.merchant_id == user_from_token.merchant_id.as_str()) + { + Some(user_role) => { + if !predefined_permissions::is_role_deletable(&user_role.role_id) { + return Err(UserErrors::InvalidRoleId.into()) + .attach_printable("Deletion not allowed for users with specific role id"); + } + } + None => { + return Err(UserErrors::InvalidDeleteOperation.into()) + .attach_printable("User is not associated with the merchant"); + } + }; + + if user_roles.len() > 1 { + state + .store + .delete_user_role_by_user_id_merchant_id( + user_from_db.get_user_id(), + user_from_token.merchant_id.as_str(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while deleting user role")?; + + Ok(ApplicationResponse::StatusOk) + } else { + state + .store + .delete_user_by_user_id(user_from_db.get_user_id()) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while deleting user entry")?; + + state + .store + .delete_user_role_by_user_id_merchant_id( + user_from_db.get_user_id(), + user_from_token.merchant_id.as_str(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while deleting user role")?; + + Ok(ApplicationResponse::StatusOk) + } +} diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs index ec24b4ed07d..8e2ac0b6ad3 100644 --- a/crates/router/src/db/dashboard_metadata.rs +++ b/crates/router/src/db/dashboard_metadata.rs @@ -36,6 +36,12 @@ pub trait DashboardMetadataInterface { org_id: &str, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] @@ -111,6 +117,21 @@ impl DashboardMetadataInterface for Store { .map_err(Into::into) .into_report() } + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id( + &conn, + user_id.to_owned(), + merchant_id.to_owned(), + ) + .await + .map_err(Into::into) + .into_report() + } } #[async_trait::async_trait] @@ -246,4 +267,31 @@ impl DashboardMetadataInterface for MockDb { } Ok(query_result) } + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + let mut dashboard_metadata = self.dashboard_metadata.lock().await; + + let initial_len = dashboard_metadata.len(); + + dashboard_metadata.retain(|metadata_inner| { + !(metadata_inner + .user_id + .clone() + .map(|user_id_inner| user_id_inner == user_id) + .unwrap_or(false) + && metadata_inner.merchant_id == merchant_id) + }); + + if dashboard_metadata.len() == initial_len { + return Err(errors::StorageError::ValueNotFound(format!( + "No user available for user_id = {user_id} and merchant id = {merchant_id}" + )) + .into()); + } + + Ok(true) + } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 8398c153156..e88d59ea9f3 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1955,9 +1955,14 @@ impl UserRoleInterface for KafkaStore { .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update) .await } - - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { - self.diesel_store.delete_user_role(user_id).await + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_user_role_by_user_id_merchant_id(user_id, merchant_id) + .await } async fn list_user_roles_by_user_id( @@ -2017,6 +2022,16 @@ impl DashboardMetadataInterface for KafkaStore { .find_merchant_scoped_dashboard_metadata(merchant_id, org_id, data_keys) .await } + + async fn delete_user_scoped_dashboard_metadata_by_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index d8938f9683d..f02e6d60b3b 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -32,8 +32,11 @@ pub trait UserRoleInterface { merchant_id: &str, update: storage::UserRoleUpdate, ) -> CustomResult<storage::UserRole, errors::StorageError>; - - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError>; + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError>; async fn list_user_roles_by_user_id( &self, @@ -100,12 +103,20 @@ impl UserRoleInterface for Store { .into_report() } - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::delete_by_user_id(&conn, user_id.to_owned()) - .await - .map_err(Into::into) - .into_report() + storage::UserRole::delete_by_user_id_merchant_id( + &conn, + user_id.to_owned(), + merchant_id.to_owned(), + ) + .await + .map_err(Into::into) + .into_report() } async fn list_user_roles_by_user_id( @@ -230,11 +241,17 @@ impl UserRoleInterface for MockDb { ) } - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; let user_role_index = user_roles .iter() - .position(|user_role| user_role.user_id == user_id) + .position(|user_role| { + user_role.user_id == user_id && user_role.merchant_id == merchant_id + }) .ok_or(errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )))?; @@ -286,8 +303,14 @@ impl UserRoleInterface for super::KafkaStore { ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store.find_user_role_by_user_id(user_id).await } - async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { - self.diesel_store.delete_user_role(user_id).await + async fn delete_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<bool, errors::StorageError> { + self.diesel_store + .delete_user_role_by_user_id_merchant_id(user_id, merchant_id) + .await } async fn list_user_roles_by_user_id( &self, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 4345109a672..5922eeb9fee 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -928,7 +928,8 @@ impl User { web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) .route(web::post().to(set_dashboard_metadata)), - ); + ) + .service(web::resource("/user/delete").route(web::delete().to(delete_user_role))); #[cfg(feature = "dummy_connector")] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1c967222dc7..30348513c2b 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -176,6 +176,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ForgotPassword | Flow::ResetPassword | Flow::InviteUser + | Flow::DeleteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmail | Flow::VerifyEmailRequest diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 73b1ef1b01d..f83134e5825 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -115,3 +115,21 @@ pub async fn accept_invitation( )) .await } + +pub async fn delete_user_role( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<user_role_api::DeleteUserRoleRequest>, +) -> HttpResponse { + let flow = Flow::DeleteUser; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload.into_inner(), + user_role_core::delete_user_role, + &auth::JWTAuth(Permission::UsersWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs index c489f1fc963..6fe0ddcc360 100644 --- a/crates/router/src/services/authorization/predefined_permissions.rs +++ b/crates/router/src/services/authorization/predefined_permissions.rs @@ -9,6 +9,7 @@ pub struct RoleInfo { permissions: Vec<Permission>, name: Option<&'static str>, is_invitable: bool, + is_deletable: bool, } impl RoleInfo { @@ -63,6 +64,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: None, is_invitable: false, + is_deletable: false, }, ); roles.insert( @@ -87,6 +89,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: None, is_invitable: false, + is_deletable: false, }, ); @@ -126,6 +129,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Organization Admin"), is_invitable: false, + is_deletable: false, }, ); @@ -165,6 +169,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Admin"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -189,6 +194,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("View Only"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -214,6 +220,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("IAM"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -239,6 +246,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Developer"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -269,6 +277,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Operator"), is_invitable: true, + is_deletable: true, }, ); roles.insert( @@ -291,6 +300,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy: ], name: Some("Customer Support"), is_invitable: true, + is_deletable: true, }, ); roles @@ -307,3 +317,9 @@ pub fn is_role_invitable(role_id: &str) -> bool { .get(role_id) .map_or(false, |role_info| role_info.is_invitable) } + +pub fn is_role_deletable(role_id: &str) -> bool { + PREDEFINED_PERMISSIONS + .get(role_id) + .map_or(false, |role_info| role_info.is_deletable) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index ba323ebc5e3..84f2e3e1267 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -321,6 +321,8 @@ pub enum Flow { ResetPassword, /// Invite users InviteUser, + /// Delete user + DeleteUser, /// Incremental Authorization flow PaymentsIncrementalAuthorization, /// Get action URL for connector onboarding
2024-01-17T13:43:09Z
## Description Add add new endpoint `/user/user/delete` that deletes the user present in the merchant account Here we have two scenarios - When user is related to more than one merchant accounts: Delete the user role for that particular merchant account. User will be present in other accounts. - When user is part of one merchant account: Delete user role and user completely. ## Motivation and Context Currently there is no endpoint to remove the invited users #
cc7e33a5751d97b44c7aba561c974f529ce8824a
- Singup/Singin Use the following curl to invite users: ``` curl --location 'http://localhost:8080/user/user/invite' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "user2@juspay.in", "name": "user2", "role_id": "merchant_admin" } ``` Use the following curl to delete invited user: ``` curl --location 'http://localhost:8080/user/user/delete' \ --header 'Authorization: Bearer JWT' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "invite_from_test21521@juspay.in" }' ``` Cases to handle: - only users with permission UsersWrite can delete - org_admin cannot be deleted - internal users cannot be deleted - user cannot delete himself
[ "crates/api_models/src/events/user_role.rs", "crates/api_models/src/user_role.rs", "crates/diesel_models/src/query/dashboard_metadata.rs", "crates/diesel_models/src/query/user_role.rs", "crates/router/src/core/errors/user.rs", "crates/router/src/core/user_role.rs", "crates/router/src/db/dashboard_metada...
juspay/hyperswitch
juspay__hyperswitch-3372
Bug: feat: update user details api
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index c0743c8b8fc..40d082d1cad 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -13,7 +13,8 @@ use crate::user::{ AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse, InviteUserRequest, InviteUserResponse, ResetPasswordRequest, SendVerifyEmailRequest, SignUpRequest, - SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UserMerchantCreate, VerifyEmailRequest, + SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, + UserMerchantCreate, VerifyEmailRequest, }; impl ApiEventMetric for DashboardEntryResponse { @@ -54,7 +55,8 @@ common_utils::impl_misc_api_event_type!( InviteUserRequest, InviteUserResponse, VerifyEmailRequest, - SendVerifyEmailRequest + SendVerifyEmailRequest, + UpdateUserAccountDetailsRequest ); #[cfg(feature = "dummy_connector")] diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index a04c4fef660..8de6a3c0b4f 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -147,3 +147,9 @@ pub struct VerifyTokenResponse { pub merchant_id: String, pub user_email: pii::Email, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct UpdateUserAccountDetailsRequest { + pub name: Option<Secret<String>>, + pub preferred_merchant_id: Option<String>, +} diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index d2f9564a530..6b408038ef5 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -19,6 +19,20 @@ impl UserRole { .await } + pub async fn find_by_user_id_merchant_id( + conn: &PgPooledConn, + user_id: String, + merchant_id: String, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::user_id + .eq(user_id) + .and(dsl::merchant_id.eq(merchant_id)), + ) + .await + } + pub async fn update_by_user_id_merchant_id( conn: &PgPooledConn, user_id: String, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 131d2b18266..c9887e1770f 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1056,6 +1056,8 @@ diesel::table! { is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, + #[max_length = 64] + preferred_merchant_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index c608f2654c6..84fe8710060 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -19,6 +19,7 @@ pub struct User { pub is_verified: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, + pub preferred_merchant_id: Option<String>, } #[derive( @@ -33,6 +34,7 @@ pub struct UserNew { pub is_verified: bool, pub created_at: Option<PrimitiveDateTime>, pub last_modified_at: Option<PrimitiveDateTime>, + pub preferred_merchant_id: Option<String>, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] @@ -42,6 +44,7 @@ pub struct UserUpdateInternal { password: Option<Secret<String>>, is_verified: Option<bool>, last_modified_at: PrimitiveDateTime, + preferred_merchant_id: Option<String>, } #[derive(Debug)] @@ -51,6 +54,7 @@ pub enum UserUpdate { name: Option<String>, password: Option<Secret<String>>, is_verified: Option<bool>, + preferred_merchant_id: Option<String>, }, } @@ -63,16 +67,19 @@ impl From<UserUpdate> for UserUpdateInternal { password: None, is_verified: Some(true), last_modified_at, + preferred_merchant_id: None, }, UserUpdate::AccountUpdate { name, password, is_verified, + preferred_merchant_id, } => Self { name, password, is_verified, last_modified_at, + preferred_merchant_id, }, } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 27a4f67618e..729cef65c20 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -253,6 +253,7 @@ pub async fn change_password( name: None, password: Some(new_password_hash), is_verified: None, + preferred_merchant_id: None, }, ) .await @@ -330,6 +331,7 @@ pub async fn reset_password( name: None, password: Some(hash_password), is_verified: Some(true), + preferred_merchant_id: None, }, ) .await @@ -786,3 +788,47 @@ pub async fn verify_token( user_email: user.email, })) } + +pub async fn update_user_details( + state: AppState, + user_token: auth::UserFromToken, + req: user_api::UpdateUserAccountDetailsRequest, +) -> UserResponse<()> { + let user: domain::UserFromStorage = state + .store + .find_user_by_id(&user_token.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + let name = req.name.map(domain::UserName::new).transpose()?; + + if let Some(ref preferred_merchant_id) = req.preferred_merchant_id { + let _ = state + .store + .find_user_role_by_user_id_merchant_id(user.get_user_id(), preferred_merchant_id) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::MerchantIdNotFound) + } else { + e.change_context(UserErrors::InternalServerError) + } + })?; + } + + let user_update = storage_user::UserUpdate::AccountUpdate { + name: name.map(|x| x.get_secret().expose()), + password: None, + is_verified: None, + preferred_merchant_id: req.preferred_merchant_id, + }; + + state + .store + .update_user_by_user_id(user.get_user_id(), user_update) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 19a83088a06..8398c153156 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1927,12 +1927,24 @@ impl UserRoleInterface for KafkaStore { ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store.insert_user_role(user_role).await } + async fn find_user_role_by_user_id( &self, user_id: &str, ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store.find_user_role_by_user_id(user_id).await } + + async fn find_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<user_storage::UserRole, errors::StorageError> { + self.diesel_store + .find_user_role_by_user_id_merchant_id(user_id, merchant_id) + .await + } + async fn update_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -1943,9 +1955,11 @@ impl UserRoleInterface for KafkaStore { .update_user_role_by_user_id_merchant_id(user_id, merchant_id, update) .await } + async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError> { self.diesel_store.delete_user_role(user_id).await } + async fn list_user_roles_by_user_id( &self, user_id: &str, diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index e3dda965f9c..ecd71f7e2c9 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -145,6 +145,7 @@ impl UserInterface for MockDb { is_verified: user_data.is_verified, created_at: user_data.created_at.unwrap_or(time_now), last_modified_at: user_data.created_at.unwrap_or(time_now), + preferred_merchant_id: user_data.preferred_merchant_id, }; users.push(user.clone()); Ok(user) @@ -207,10 +208,14 @@ impl UserInterface for MockDb { name, password, is_verified, + preferred_merchant_id, } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), password: password.clone().unwrap_or(user.password.clone()), is_verified: is_verified.unwrap_or(user.is_verified), + preferred_merchant_id: preferred_merchant_id + .clone() + .or(user.preferred_merchant_id.clone()), ..user.to_owned() }, }; diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index bf84ae134ea..d8938f9683d 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -14,16 +14,25 @@ pub trait UserRoleInterface { &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError>; + async fn find_user_role_by_user_id( &self, user_id: &str, ) -> CustomResult<storage::UserRole, errors::StorageError>; + + async fn find_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<storage::UserRole, errors::StorageError>; + async fn update_user_role_by_user_id_merchant_id( &self, user_id: &str, merchant_id: &str, update: storage::UserRoleUpdate, ) -> CustomResult<storage::UserRole, errors::StorageError>; + async fn delete_user_role(&self, user_id: &str) -> CustomResult<bool, errors::StorageError>; async fn list_user_roles_by_user_id( @@ -57,6 +66,22 @@ impl UserRoleInterface for Store { .into_report() } + async fn find_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<storage::UserRole, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::UserRole::find_by_user_id_merchant_id( + &conn, + user_id.to_owned(), + merchant_id.to_owned(), + ) + .await + .map_err(Into::into) + .into_report() + } + async fn update_user_role_by_user_id_merchant_id( &self, user_id: &str, @@ -148,6 +173,24 @@ impl UserRoleInterface for MockDb { ) } + async fn find_user_role_by_user_id_merchant_id( + &self, + user_id: &str, + merchant_id: &str, + ) -> CustomResult<storage::UserRole, errors::StorageError> { + let user_roles = self.user_roles.lock().await; + user_roles + .iter() + .find(|user_role| user_role.user_id == user_id && user_role.merchant_id == merchant_id) + .cloned() + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No user role available for user_id = {user_id} and merchant_id = {merchant_id}" + )) + .into(), + ) + } + async fn update_user_role_by_user_id_merchant_id( &self, user_id: &str, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0c489dbe63a..0807fb0800e 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -921,6 +921,7 @@ impl User { .service(web::resource("/role/list").route(web::get().to(list_roles))) .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) .service(web::resource("/user/invite").route(web::post().to(invite_user))) + .service(web::resource("/update").route(web::post().to(update_user_account_details))) .service( web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 12cf76be475..805fb115264 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -178,7 +178,8 @@ impl From<Flow> for ApiIdentifier { | Flow::InviteUser | Flow::UserSignUpWithMerchantId | Flow::VerifyEmail - | Flow::VerifyEmailRequest => Self::User, + | Flow::VerifyEmailRequest + | Flow::UpdateUserAccountDetails => Self::User, Flow::ListRoles | Flow::GetRole | Flow::UpdateUserRole | Flow::GetAuthorizationInfo => { Self::UserRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 976fd5c9f56..eca32318adf 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -403,3 +403,21 @@ pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpReques )) .await } + +pub async fn update_user_account_details( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::UpdateUserAccountDetailsRequest>, +) -> HttpResponse { + let flow = Flow::UpdateUserAccountDetails; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + json_payload.into_inner(), + user_core::update_user_details, + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 0d6636e567d..c4e0aa3f3ea 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -331,6 +331,8 @@ pub enum Flow { VerifyEmail, /// Send verify email VerifyEmailRequest, + /// Update user account details + UpdateUserAccountDetails, } /// diff --git a/migrations/2024-01-02-111223_users_preferred_merchant_column/down.sql b/migrations/2024-01-02-111223_users_preferred_merchant_column/down.sql new file mode 100644 index 00000000000..b9160b6f105 --- /dev/null +++ b/migrations/2024-01-02-111223_users_preferred_merchant_column/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE users DROP COLUMN preferred_merchant_id; diff --git a/migrations/2024-01-02-111223_users_preferred_merchant_column/up.sql b/migrations/2024-01-02-111223_users_preferred_merchant_column/up.sql new file mode 100644 index 00000000000..77567ce93fa --- /dev/null +++ b/migrations/2024-01-02-111223_users_preferred_merchant_column/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE users ADD COLUMN preferred_merchant_id VARCHAR(64);
2024-01-17T12:44:24Z
## Description <!-- Describe your changes in detail --> - This PR adds a new column in users table called `preferred_merchant_id`. `preferred_merchant_id` will be used at the time of signin to directly use that `merchant_id` when user has access to multiple merchant accounts. - This PR adds a new API which enables users to update their name and preferred merchant id. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> To support the highlighted flow in the following diagram. Note: This PR doesn't have the actual changes of the flow, but has few required changes to make the highlighted flow possible. ```mermaid flowchart TD A["Connect Account"] -- Email --> B{"User Exists"} B -- No --> C["Create new \n Org \n Merchant \n User \n User Role"] C --> D["Send Verify Email"] D --> E["Verify Email Token"] B -- Yes --> D E --> H{"Is there\n any perferred \nmerchant"} F -- ==0 --> I{{"Send list of \nmerchants which\n user has access to\n along with an\n intermediate token"}} F -- >1 --> G[Select the first role with active status] subgraph Preferred Merchant H -- Yes --> M["Send the token \nwith that merchant_id"] end H -- No --> F{"How many \n active merchants\n does user have \naccess to"} I -- merchant_ids, \nintermediate_token --> O["Accept Invite"] O --> P["Change status to active"] P --> G G --> M K["Sign In"] -- Email, Password --> H ``` #
eb2a61d8597995838f21b8233653c691118b2191
Postman. ```curl curl --location 'http://localhost:8080/user/update' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "name": "user name", // Optional "preferred_merchant_id": "merchant_id" // Optional, user should have access to this merchant_id }' ``` If the api is successful, the db will be updated and the response will be 200 OK.
[ "crates/api_models/src/events/user.rs", "crates/api_models/src/user.rs", "crates/diesel_models/src/query/user_role.rs", "crates/diesel_models/src/schema.rs", "crates/diesel_models/src/user.rs", "crates/router/src/core/user.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/db/user.rs", "...
juspay/hyperswitch
juspay__hyperswitch-3699
Bug: [FIX] add unresponsive timeout for redis This will check if a connection is unresponsive, if it is it will try to re-construct the connection
diff --git a/Cargo.lock b/Cargo.lock index 2c9293c1701..b466a161097 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2610,9 +2610,9 @@ dependencies = [ [[package]] name = "fred" -version = "7.1.0" +version = "7.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9282e65613822eea90c99872c51afa1de61542215cb11f91456a93f50a5a131a" +checksum = "b99c2b48934cd02a81032dd7428b7ae831a27794275bc94eba367418db8a9e55" dependencies = [ "arc-swap", "async-trait", diff --git a/config/config.example.toml b/config/config.example.toml index abe3f6b4e08..028f689d796 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -54,9 +54,10 @@ use_legacy_version = false # Resp protocol for fred crate (set this to tr stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible. disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled. -max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. -default_command_timeout = 0 # An optional timeout to apply to all commands. -max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. +max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. +default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds +unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout. +max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. # This section provides configs for currency conversion api [forex_api] diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index c8c118d9827..990796c79bc 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -169,9 +169,10 @@ use_legacy_version = false # RESP p stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible. disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled. -max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. -default_command_timeout = 0 # An optional timeout to apply to all commands. -max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. +max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied. +default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds +unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout. +max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing. cluster_enabled = true # boolean cluster_urls = ["redis.cluster.uri-1:8080", "redis.cluster.uri-2:4115"] # List of redis cluster urls diff --git a/config/development.toml b/config/development.toml index d69719bd419..2fab7deeb3e 100644 --- a/config/development.toml +++ b/config/development.toml @@ -44,7 +44,8 @@ stream_read_count = 1 auto_pipeline = true disable_auto_backpressure = false max_in_flight_commands = 5000 -default_command_timeout = 0 +default_command_timeout = 30 +unresponsive_timeout = 10 max_feed_count = 200 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8170132bb85..e0de31dfbb7 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -78,7 +78,8 @@ stream_read_count = 1 auto_pipeline = true disable_auto_backpressure = false max_in_flight_commands = 5000 -default_command_timeout = 0 +default_command_timeout = 30 +unresponsive_timeout = 10 max_feed_count = 200 [cors] diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml index 32e850a073f..85cfef3df54 100644 --- a/crates/redis_interface/Cargo.toml +++ b/crates/redis_interface/Cargo.toml @@ -9,7 +9,7 @@ license.workspace = true [dependencies] error-stack = "0.3.1" -fred = { version = "7.0.0", features = ["metrics", "partial-tracing", "subscriber-client"] } +fred = { version = "7.1.2", features = ["metrics", "partial-tracing", "subscriber-client", "check-unresponsive"] } futures = "0.3" serde = { version = "1.0.193", features = ["derive"] } thiserror = "1.0.40" diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs index 33d40ebe155..b46e4aec191 100644 --- a/crates/redis_interface/src/lib.rs +++ b/crates/redis_interface/src/lib.rs @@ -132,6 +132,11 @@ impl RedisConnectionPool { }, }; + let connection_config = fred::types::ConnectionConfig { + unresponsive_timeout: std::time::Duration::from_secs(conf.unresponsive_timeout), + ..fred::types::ConnectionConfig::default() + }; + if !conf.use_legacy_version { config.version = fred::types::RespVersion::RESP3; } @@ -151,7 +156,7 @@ impl RedisConnectionPool { let pool = fred::prelude::RedisPool::new( config, Some(perf), - None, + Some(connection_config), Some(reconnect_policy), conf.pool_size, ) @@ -201,6 +206,15 @@ impl RedisConnectionPool { } } } + + pub async fn on_unresponsive(&self) { + let _ = self.pool.clients().iter().map(|client| { + client.on_unresponsive(|server| { + logger::warn!(redis_server =?server.host, "Redis server is unresponsive"); + Ok(()) + }) + }); + } } struct RedisConfig { diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index 4ebb620c36a..cb883fc1693 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -57,6 +57,7 @@ pub struct RedisSettings { pub max_in_flight_commands: u64, pub default_command_timeout: u64, pub max_feed_count: u64, + pub unresponsive_timeout: u64, } impl RedisSettings { @@ -76,7 +77,17 @@ impl RedisSettings { "Redis `cluster_urls` must be specified if `cluster_enabled` is `true`".into(), )) .into_report() - }) + })?; + + when( + self.default_command_timeout < self.unresponsive_timeout, + || { + Err(errors::RedisError::InvalidConfiguration( + "Unresponsive timeout cannot be greater than the command timeout".into(), + )) + .into_report() + }, + ) } } @@ -97,8 +108,9 @@ impl Default for RedisSettings { auto_pipeline: true, disable_auto_backpressure: false, max_in_flight_commands: 5000, - default_command_timeout: 0, + default_command_timeout: 30, max_feed_count: 200, + unresponsive_timeout: 10, } } }
2024-01-17T08:43:10Z
## Description <!-- Describe your changes in detail --> Enable `check-unresponsive` in fred and update the version to `7.1.2` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This will retry the command automatically every second(ref: https://github.com/aembke/fred.rs/blob/52bff989263b8bb27030be4e20fd313e65608b44/examples/globals.rs#L22) until `unresponsive_timeout` is exhausted. For retry it tries if one succeeds other will be discarded(ref: https://github.com/aembke/fred.rs/blob/52bff989263b8bb27030be4e20fd313e65608b44/src/router/utils.rs#L566) . #
15b367eb792448fb3f3312484ab13dd8241d4a14
- Sanity Test with Payments and Refunds. **This change cannot be tested since we cannot reproduce the situation in sandbox**
[ "Cargo.lock", "config/config.example.toml", "config/deployments/env_specific.toml", "config/development.toml", "config/docker_compose.toml", "crates/redis_interface/Cargo.toml", "crates/redis_interface/src/lib.rs", "crates/redis_interface/src/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3366
Bug: feat(invite): make accept invite api
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index aa8d13dab6d..c8d8fd96a7a 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -1,8 +1,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ - AuthorizationInfoResponse, GetRoleRequest, ListRolesResponse, RoleInfoResponse, - UpdateUserRoleRequest, + AcceptInvitationRequest, AuthorizationInfoResponse, GetRoleRequest, ListRolesResponse, + RoleInfoResponse, UpdateUserRoleRequest, }; common_utils::impl_misc_api_event_type!( @@ -10,5 +10,6 @@ common_utils::impl_misc_api_event_type!( RoleInfoResponse, GetRoleRequest, AuthorizationInfoResponse, - UpdateUserRoleRequest + UpdateUserRoleRequest, + AcceptInvitationRequest ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index b057f8ca8bc..d2548935f62 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -1,3 +1,5 @@ +use crate::user::DashboardEntryResponse; + #[derive(Debug, serde::Serialize)] pub struct ListRolesResponse(pub Vec<RoleInfoResponse>); @@ -91,3 +93,11 @@ pub enum UserStatus { Active, InvitationSent, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct AcceptInvitationRequest { + pub merchant_ids: Vec<String>, + pub need_dashboard_entry_response: Option<bool>, +} + +pub type AcceptInvitationResponse = DashboardEntryResponse; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 729cef65c20..3384e229009 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -90,11 +90,10 @@ pub async fn signup( UserStatus::Active, ) .await?; - let token = - utils::user::generate_jwt_auth_token(state.clone(), &user_from_db, &user_role).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(state, user_from_db, user_role, token)?, + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, )) } @@ -118,11 +117,10 @@ pub async fn signin( user_from_db.compare_password(request.password)?; let user_role = user_from_db.get_role_from_db(state.clone()).await?; - let token = - utils::user::generate_jwt_auth_token(state.clone(), &user_from_db, &user_role).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(state, user_from_db, user_role, token)?, + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, )) } @@ -600,7 +598,7 @@ pub async fn switch_merchant_id( .ok_or(UserErrors::InvalidRoleOperation.into()) .attach_printable("User doesn't have access to switch")?; - let token = utils::user::generate_jwt_auth_token(state, &user, user_role).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user, user_role).await?; (token, user_role.role_id.clone()) }; @@ -712,11 +710,10 @@ pub async fn verify_email( let user_from_db: domain::UserFromStorage = user.into(); let user_role = user_from_db.get_role_from_db(state.clone()).await?; - let token = - utils::user::generate_jwt_auth_token(state.clone(), &user_from_db, &user_role).await?; + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; Ok(ApplicationResponse::Json( - utils::user::get_dashboard_entry_response(state, user_from_db, user_role, token)?, + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, )) } diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index d8ff836e1f8..245f8d246d2 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -1,6 +1,7 @@ use api_models::user_role as user_role_api; -use diesel_models::user_role::UserRoleUpdate; +use diesel_models::{enums::UserStatus, user_role::UserRoleUpdate}; use error_stack::ResultExt; +use router_env::logger; use crate::{ core::errors::{UserErrors, UserResponse}, @@ -115,3 +116,48 @@ pub async fn update_user_role( Ok(ApplicationResponse::StatusOk) } + +pub async fn accept_invitation( + state: AppState, + user_token: auth::UserWithoutMerchantFromToken, + req: user_role_api::AcceptInvitationRequest, +) -> UserResponse<user_role_api::AcceptInvitationResponse> { + let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async { + state + .store + .update_user_role_by_user_id_merchant_id( + user_token.user_id.as_str(), + merchant_id, + UserRoleUpdate::UpdateStatus { + status: UserStatus::Active, + modified_by: user_token.user_id.clone(), + }, + ) + .await + .map_err(|e| { + logger::error!("Error while accepting invitation {}", e); + }) + .ok() + })) + .await + .into_iter() + .reduce(Option::or) + .flatten() + .ok_or(UserErrors::MerchantIdNotFound)?; + + if let Some(true) = req.need_dashboard_entry_response { + let user_from_db = state + .store + .find_user_by_id(user_token.user_id.as_str()) + .await + .change_context(UserErrors::InternalServerError)? + .into(); + + let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?; + return Ok(ApplicationResponse::Json( + utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?, + )); + } + + Ok(ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 3d63df2fe80..4345109a672 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -922,6 +922,7 @@ impl User { .service(web::resource("/role").route(web::get().to(get_role_from_token))) .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) .service(web::resource("/user/invite").route(web::post().to(invite_user))) + .service(web::resource("/user/invite/accept").route(web::post().to(accept_invitation))) .service(web::resource("/update").route(web::post().to(update_user_account_details))) .service( web::resource("/data") diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index d3a2e1af9a7..1c967222dc7 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -185,7 +185,8 @@ impl From<Flow> for ApiIdentifier { | Flow::GetRole | Flow::GetRoleFromToken | Flow::UpdateUserRole - | Flow::GetAuthorizationInfo => Self::UserRole, + | Flow::GetAuthorizationInfo + | Flow::AcceptInvitation => Self::UserRole, Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index fe305942d03..73b1ef1b01d 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -96,3 +96,22 @@ pub async fn update_user_role( )) .await } + +pub async fn accept_invitation( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_role_api::AcceptInvitationRequest>, +) -> HttpResponse { + let flow = Flow::AcceptInvitation; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload, + user_role_core::accept_invitation, + &auth::UserWithoutMerchantJWTAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 3370912394e..eaadc0d5c7b 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -55,6 +55,9 @@ pub enum AuthenticationType { merchant_id: String, user_id: Option<String>, }, + UserJwt { + user_id: String, + }, MerchantId { merchant_id: String, }, @@ -81,11 +84,32 @@ impl AuthenticationType { user_id: _, } | Self::WebhookAuth { merchant_id } => Some(merchant_id.as_ref()), - Self::AdminApiKey | Self::NoAuth => None, + Self::AdminApiKey | Self::UserJwt { .. } | Self::NoAuth => None, } } } +#[derive(Clone, Debug)] +pub struct UserWithoutMerchantFromToken { + pub user_id: String, +} + +#[derive(serde::Serialize, serde::Deserialize)] +pub struct UserAuthToken { + pub user_id: String, + pub exp: u64, +} + +#[cfg(feature = "olap")] +impl UserAuthToken { + pub async fn new_token(user_id: String, settings: &settings::Settings) -> UserResult<String> { + let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); + let exp = jwt::generate_exp(exp_duration)?.as_secs(); + let token_payload = Self { user_id, exp }; + jwt::generate_jwt(&token_payload, settings).await + } +} + #[derive(serde::Serialize, serde::Deserialize)] pub struct AuthToken { pub user_id: String, @@ -276,6 +300,33 @@ pub async fn get_admin_api_key( .await } +#[derive(Debug)] +pub struct UserWithoutMerchantJWTAuth; + +#[cfg(feature = "olap")] +#[async_trait] +impl<A> AuthenticateAndFetch<UserWithoutMerchantFromToken, A> for UserWithoutMerchantJWTAuth +where + A: AppStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(UserWithoutMerchantFromToken, AuthenticationType)> { + let payload = parse_jwt_payload::<A, UserAuthToken>(request_headers, state).await?; + + Ok(( + UserWithoutMerchantFromToken { + user_id: payload.user_id.clone(), + }, + AuthenticationType::UserJwt { + user_id: payload.user_id, + }, + )) + } +} + #[derive(Debug)] pub struct AdminApiAuth; diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 53c88f8aea1..bbe21f289aa 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -739,7 +739,7 @@ impl UserFromStorage { } #[cfg(feature = "email")] - pub fn get_verification_days_left(&self, state: AppState) -> UserResult<Option<i64>> { + pub fn get_verification_days_left(&self, state: &AppState) -> UserResult<Option<i64>> { if self.0.is_verified { return Ok(None); } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index a115fa2a2d8..a3f9e7978aa 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -56,7 +56,7 @@ impl UserFromToken { } pub async fn generate_jwt_auth_token( - state: AppState, + state: &AppState, user: &UserFromStorage, user_role: &UserRole, ) -> UserResult<Secret<String>> { @@ -89,17 +89,13 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes( Ok(Secret::new(token)) } -#[allow(unused_variables)] pub fn get_dashboard_entry_response( - state: AppState, + state: &AppState, user: UserFromStorage, user_role: UserRole, token: Secret<String>, ) -> UserResult<user_api::DashboardEntryResponse> { - #[cfg(feature = "email")] - let verification_days_left = user.get_verification_days_left(state)?; - #[cfg(not(feature = "email"))] - let verification_days_left = None; + let verification_days_left = get_verification_days_left(state, &user)?; Ok(user_api::DashboardEntryResponse { merchant_id: user_role.merchant_id, @@ -111,3 +107,14 @@ pub fn get_dashboard_entry_response( user_role: user_role.role_id, }) } + +#[allow(unused_variables)] +pub fn get_verification_days_left( + state: &AppState, + user: &UserFromStorage, +) -> UserResult<Option<i64>> { + #[cfg(feature = "email")] + return user.get_verification_days_left(state); + #[cfg(not(feature = "email"))] + return Ok(None); +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 7e3a692517f..ba323ebc5e3 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -335,6 +335,8 @@ pub enum Flow { VerifyEmailRequest, /// Update user account details UpdateUserAccountDetails, + /// Accept user invitation + AcceptInvitation, } ///
2024-01-17T07:14:02Z
## Description <!-- Describe your changes in detail --> This PR will add a new API for accepting invitation and also a new JWT auth type which has only `user_id`. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> To support the Accept Invite flow in the following flow. ```mermaid flowchart TD A["Connect Account"] -- Email --> B{"User Exists"} B -- No --> C["Create new \n Org \n Merchant \n User \n User Role"] C --> D["Send Verify Email"] D --> E["Verify Email Token"] B -- Yes --> D E --> H{"Is there\n any perferred \nmerchant"} F -- ==0 --> I{{"Send list of \nmerchants which\n user has access to\n along with an\n intermediate token"}} F -- >1 --> G[Select the first role with active status] H -- Yes --> M["Send the token \nwith that merchant_id"] H -- No --> F{"How many \n active merchants\n does user have \naccess to"} I -- merchant_ids, \nintermediate_token --> O["Accept Invite"] subgraph Accept Invite O --> P["Change status to active"] P --> G G --> M end K["Sign In"] -- Email, Password --> H ``` #
1c04ac751240f5c931df0f282af1e0ad745e9509
```curl curl --location 'http://localhost:8080/user/user/invite/accept' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "merchant_ids": [ "merchant_id1", "merchant_id2", "merchant_id3" ], "need_dashboard_entry_response": true }' ``` If any of the `merchant_id` status is `active`, then you will be getting the following response. ``` { "token": "JWT with merchant_id, user_id, user_role", "merchant_id": "merchant_id", "name": "user name", "email": "user email", "verification_days_left": null, "user_role": "user role" } ``` If `need_dashboard_entry_response` is `false` or not sent, then the response will be 200 OK.
[ "crates/api_models/src/events/user_role.rs", "crates/api_models/src/user_role.rs", "crates/router/src/core/user.rs", "crates/router/src/core/user_role.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/lock_utils.rs", "crates/router/src/routes/user_role.rs", "crates/router/src/services/...
juspay/hyperswitch
juspay__hyperswitch-3497
Bug: [FIX] add a metric while pushing data to drainer stream
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index 7e2c7f2fc3c..d31f05b4979 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -225,6 +225,11 @@ impl<T: DatabaseStore> KVRouterStore<T> { .change_context(RedisError::JsonSerializationFailed)?, ) .await + .map(|_| metrics::KV_PUSHED_TO_DRAINER.add(&metrics::CONTEXT, 1, &[])) + .map_err(|err| { + metrics::KV_FAILED_TO_PUSH_TO_DRAINER.add(&metrics::CONTEXT, 1, &[]); + err + }) .change_context(RedisError::StreamAppendFailed) } } diff --git a/crates/storage_impl/src/metrics.rs b/crates/storage_impl/src/metrics.rs index 3310e458879..29bca2a007b 100644 --- a/crates/storage_impl/src/metrics.rs +++ b/crates/storage_impl/src/metrics.rs @@ -8,3 +8,5 @@ counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses // Metrics for KV counter_metric!(KV_OPERATION_SUCCESSFUL, GLOBAL_METER); counter_metric!(KV_OPERATION_FAILED, GLOBAL_METER); +counter_metric!(KV_PUSHED_TO_DRAINER, GLOBAL_METER); +counter_metric!(KV_FAILED_TO_PUSH_TO_DRAINER, GLOBAL_METER);
2024-01-17T05:25:30Z
## Description <!-- Describe your changes in detail --> Add a metric to indicate data was pushed to drainer ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Add a proper metrics to indicate data was pushed/failed while pushing to drainer #
398c5ed51e0547504c3dfbd1d7c23568337e7d1c
- Do a transaction through KV merchant - Check `KV_PUSHED_TO_DRAINER` on grafana keeping data source as `vm-single` ![Screenshot 2024-01-30 at 4 10 56 PM](https://github.com/juspay/hyperswitch/assets/43412619/5c7dbfdc-253f-4895-985a-5bc674a56de4)
[ "crates/storage_impl/src/lib.rs", "crates/storage_impl/src/metrics.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3362
Bug: bug: sample data generation with profile id When trying to generate sample data for users with multiple business profiles, we are getting 500 if the profile id is not passed in the payload.
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index dcf635595e0..3fa2a10629e 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -52,7 +52,7 @@ pub async fn generate_sample_data( let business_label_default = merchant_parsed_details.first().map(|x| x.business.clone()); - let profile_id = crate::core::utils::get_profile_id_from_business_details( + let profile_id = match crate::core::utils::get_profile_id_from_business_details( business_country_default, business_label_default.as_ref(), &merchant_from_db, @@ -61,8 +61,25 @@ pub async fn generate_sample_data( false, ) .await - .change_context(SampleDataError::InternalServerError) - .attach_printable("Failed to get business profile")?; + { + Ok(id) => id.clone(), + Err(error) => { + router_env::logger::error!( + "Profile ID not found in business details. Attempting to fetch from the database {error:?}" + ); + + state + .store + .list_business_profile_by_merchant_id(&merchant_id) + .await + .change_context(SampleDataError::InternalServerError) + .attach_printable("Failed to get business profile")? + .first() + .ok_or(SampleDataError::InternalServerError)? + .profile_id + .clone() + } + }; // 10 percent payments should be failed #[allow(clippy::as_conversions)]
2024-01-16T10:08:50Z
## Description Currently for user with multiple business profiles. We are getting 500 if the profile id is not passed in the payload. Therefore, need to fetch the profile_id (the first one) from list of business profiles, for the sample data generation. ## Motivation and Context Getting 500, for users with multiple business profiles for sample data generation. #
5ad3f8939afafce3eec39704dcaa92270b384dcd
Singup ``` curl --location 'http://localhost:8080/user/signup' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --data-raw '{ "email": "profile_test@juspay.in", "password": "Test@12345", "country": "IN" }' ``` Creating New business profile: pass current merchant_id for the endpoint ``` curl --location 'http://localhost:8080/account/merchant_1705399107/business_profile' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ "profile_name": "default5" }' ``` Generate Sample Data: ``` curl --location 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` Response will be 200
[ "crates/router/src/utils/user/sample_data.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3355
Bug: [REFACTOR]: [Cybersource] Recurring Mandates Payments Flow ### Feature Description In recurring subsequent mandate payment (MIT) the payment was getting processed with card fetched from locker, it should being processed with `connector_mandate_id` ### Possible Implementation Implement a check over `connector_mandate_id` rather than checking over Payment Method Data ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index b300e97b44a..ac2d16c9610 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -785,7 +785,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - if req.is_three_ds() && req.request.is_card() { + if req.is_three_ds() + && req.request.is_card() + && req.request.connector_mandate_id().is_none() + { Ok(format!( "{}risk/v1/authentication-setups", api::ConnectorCommon::base_url(self, connectors) @@ -809,7 +812,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req.request.amount, req, ))?; - if req.is_three_ds() && req.request.is_card() { + if req.is_three_ds() + && req.request.is_card() + && req.request.connector_mandate_id().is_none() + { let connector_req = cybersource::CybersourceAuthSetupRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -845,7 +851,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - if data.is_three_ds() && data.request.is_card() { + if data.is_three_ds() + && data.request.is_card() + && data.request.connector_mandate_id().is_none() + { let response: cybersource::CybersourceAuthSetupResponse = res .response .parse_struct("Cybersource AuthSetupResponse") diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index e83b23603e9..8beb81d9236 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -342,7 +342,7 @@ pub struct ApplePayPaymentInformation { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MandatePaymentInformation { - payment_instrument: Option<CybersoucrePaymentInstrument>, + payment_instrument: CybersoucrePaymentInstrument, } #[derive(Debug, Serialize)] @@ -482,7 +482,7 @@ impl ), ) -> Self { let (action_list, action_token_types, authorization_options) = - if item.router_data.request.setup_future_usage.is_some() { + if item.router_data.request.setup_mandate_details.is_some() { ( Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![CybersourceActionsTokenType::PaymentInstrument]), @@ -871,139 +871,168 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> fn try_from( item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - match item.router_data.request.payment_method_data.clone() { - payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), - payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data { - payments::WalletData::ApplePay(apple_pay_data) => { - match item.router_data.payment_method_token.clone() { - Some(payment_method_token) => match payment_method_token { - types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { - Self::try_from((item, decrypt_data)) - } - types::PaymentMethodToken::Token(_) => { - Err(errors::ConnectorError::InvalidWalletToken)? - } - }, - None => { - let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; - let order_information = OrderInformationWithBill::from((item, bill_to)); - let processing_information = ProcessingInformation::from(( - item, - Some(PaymentSolution::ApplePay), - )); - let client_reference_information = - ClientReferenceInformation::from(item); - let payment_information = PaymentInformation::ApplePayToken( - ApplePayTokenPaymentInformation { - fluid_data: FluidData { - value: Secret::from(apple_pay_data.payment_data), - }, - tokenized_card: ApplePayTokenizedCard { - transaction_type: TransactionType::ApplePay, - }, + match item.router_data.request.connector_mandate_id() { + Some(connector_mandate_id) => Self::try_from((item, connector_mandate_id)), + None => { + match item.router_data.request.payment_method_data.clone() { + payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + payments::WalletData::ApplePay(apple_pay_data) => { + match item.router_data.payment_method_token.clone() { + Some(payment_method_token) => match payment_method_token { + types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { + Self::try_from((item, decrypt_data)) + } + types::PaymentMethodToken::Token(_) => { + Err(errors::ConnectorError::InvalidWalletToken)? + } }, - ); - let merchant_defined_information = - item.router_data.request.metadata.clone().map(|metadata| { - Vec::<MerchantDefinedInformation>::foreign_from( - metadata.peek().to_owned(), - ) - }); - - Ok(Self { - processing_information, - payment_information, - order_information, - client_reference_information, - merchant_defined_information, - consumer_authentication_information: None, - }) + None => { + let email = item.router_data.request.get_email()?; + let bill_to = + build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = + OrderInformationWithBill::from((item, bill_to)); + let processing_information = ProcessingInformation::from(( + item, + Some(PaymentSolution::ApplePay), + )); + let client_reference_information = + ClientReferenceInformation::from(item); + let payment_information = PaymentInformation::ApplePayToken( + ApplePayTokenPaymentInformation { + fluid_data: FluidData { + value: Secret::from(apple_pay_data.payment_data), + }, + tokenized_card: ApplePayTokenizedCard { + transaction_type: TransactionType::ApplePay, + }, + }, + ); + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from( + metadata.peek().to_owned(), + ) + }); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + merchant_defined_information, + consumer_authentication_information: None, + }) + } + } + } + payments::WalletData::GooglePay(google_pay_data) => { + Self::try_from((item, google_pay_data)) } + payments::WalletData::AliPayQr(_) + | payments::WalletData::AliPayRedirect(_) + | payments::WalletData::AliPayHkRedirect(_) + | payments::WalletData::MomoRedirect(_) + | payments::WalletData::KakaoPayRedirect(_) + | payments::WalletData::GoPayRedirect(_) + | payments::WalletData::GcashRedirect(_) + | payments::WalletData::ApplePayRedirect(_) + | payments::WalletData::ApplePayThirdPartySdk(_) + | payments::WalletData::DanaRedirect {} + | payments::WalletData::GooglePayRedirect(_) + | payments::WalletData::GooglePayThirdPartySdk(_) + | payments::WalletData::MbWayRedirect(_) + | payments::WalletData::MobilePayRedirect(_) + | payments::WalletData::PaypalRedirect(_) + | payments::WalletData::PaypalSdk(_) + | payments::WalletData::SamsungPay(_) + | payments::WalletData::TwintRedirect {} + | payments::WalletData::VippsRedirect {} + | payments::WalletData::TouchNGoRedirect(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::WeChatPayQr(_) + | payments::WalletData::CashappQr(_) + | payments::WalletData::SwishQr(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message( + "Cybersource", + ), + ) + .into()) + } + }, + // If connector_mandate_id is present MandatePayment will be the PMD, the case will be handled in the first `if` clause. + // This is a fallback implementation in the event of catastrophe. + payments::PaymentMethodData::MandatePayment => { + let connector_mandate_id = + item.router_data.request.connector_mandate_id().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "connector_mandate_id", + }, + )?; + Self::try_from((item, connector_mandate_id)) + } + payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ) + .into()) } } - payments::WalletData::GooglePay(google_pay_data) => { - Self::try_from((item, google_pay_data)) - } - payments::WalletData::AliPayQr(_) - | payments::WalletData::AliPayRedirect(_) - | payments::WalletData::AliPayHkRedirect(_) - | payments::WalletData::MomoRedirect(_) - | payments::WalletData::KakaoPayRedirect(_) - | payments::WalletData::GoPayRedirect(_) - | payments::WalletData::GcashRedirect(_) - | payments::WalletData::ApplePayRedirect(_) - | payments::WalletData::ApplePayThirdPartySdk(_) - | payments::WalletData::DanaRedirect {} - | payments::WalletData::GooglePayRedirect(_) - | payments::WalletData::GooglePayThirdPartySdk(_) - | payments::WalletData::MbWayRedirect(_) - | payments::WalletData::MobilePayRedirect(_) - | payments::WalletData::PaypalRedirect(_) - | payments::WalletData::PaypalSdk(_) - | payments::WalletData::SamsungPay(_) - | payments::WalletData::TwintRedirect {} - | payments::WalletData::VippsRedirect {} - | payments::WalletData::TouchNGoRedirect(_) - | payments::WalletData::WeChatPayRedirect(_) - | payments::WalletData::WeChatPayQr(_) - | payments::WalletData::CashappQr(_) - | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Cybersource"), - ) - .into()), - }, - payments::PaymentMethodData::MandatePayment => { - let processing_information = ProcessingInformation::from((item, None)); - let payment_instrument = - item.router_data - .request - .connector_mandate_id() - .map(|mandate_token_id| CybersoucrePaymentInstrument { - id: mandate_token_id, - }); - - let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; - let order_information = OrderInformationWithBill::from((item, bill_to)); - let payment_information = - PaymentInformation::MandatePayment(MandatePaymentInformation { - payment_instrument, - }); - let client_reference_information = ClientReferenceInformation::from(item); - let merchant_defined_information = - item.router_data.request.metadata.clone().map(|metadata| { - Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) - }); - Ok(Self { - processing_information, - payment_information, - order_information, - client_reference_information, - merchant_defined_information, - consumer_authentication_information: None, - }) - } - payments::PaymentMethodData::CardRedirect(_) - | payments::PaymentMethodData::PayLater(_) - | payments::PaymentMethodData::BankRedirect(_) - | payments::PaymentMethodData::BankDebit(_) - | payments::PaymentMethodData::BankTransfer(_) - | payments::PaymentMethodData::Crypto(_) - | payments::PaymentMethodData::Reward - | payments::PaymentMethodData::Upi(_) - | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) - | payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Cybersource"), - ) - .into()) } } } } +impl + TryFrom<( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + String, + )> for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, connector_mandate_id): ( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + String, + ), + ) -> Result<Self, Self::Error> { + let processing_information = ProcessingInformation::from((item, None)); + let payment_instrument = CybersoucrePaymentInstrument { + id: connector_mandate_id, + }; + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + let payment_information = + PaymentInformation::MandatePayment(MandatePaymentInformation { payment_instrument }); + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + merchant_defined_information, + consumer_authentication_information: None, + }) + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceAuthSetupRequest { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 9eb06d675a0..ad463fcf2b9 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1524,12 +1524,12 @@ pub fn build_redirection_form( // This is the iframe recommended by cybersource but the redirection happens inside this iframe once otp // is received and we lose control of the redirection on user client browser, so to avoid that we have removed this iframe and directly consumed it. // (PreEscaped(r#"<iframe id="step_up_iframe" style="border: none; margin-left: auto; margin-right: auto; display: block" height="800px" width="400px" name="stepUpIframe"></iframe>"#)) - (PreEscaped(format!("<form id=\"step_up_form\" method=\"POST\" action=\"{step_up_url}\"> - <input id=\"step_up_form_jwt_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> + (PreEscaped(format!("<form id=\"step-up-form\" method=\"POST\" action=\"{step_up_url}\"> + <input type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> </form>"))) (PreEscaped(r#"<script> window.onload = function() { - var stepUpForm = document.querySelector('#step_up_form'); if(stepUpForm) stepUpForm.submit(); + var stepUpForm = document.querySelector('#step-up-form'); if(stepUpForm) stepUpForm.submit(); } </script>"#)) }}
2024-01-16T05:35:03Z
## Description <!-- Describe your changes in detail --> In recurring subsequent mandate payment (MIT) the payment was getting processed with card fetched from locker, now it is being processed with `connector_mandate_id` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
398c5ed51e0547504c3dfbd1d7c23568337e7d1c
- Create a CIT with zero and non-zero amount <img width="1296" alt="Screenshot 2024-01-16 at 11 06 18 AM" src="https://github.com/juspay/hyperswitch/assets/55536657/e746049b-257e-4808-9587-583b7b2c78ef"> <img width="1285" alt="Screenshot 2024-01-16 at 11 06 50 AM" src="https://github.com/juspay/hyperswitch/assets/55536657/38888a7c-89ee-4e28-826f-f600a4c2780d"> - Create MIT using Mandate ID <img width="1278" alt="Screenshot 2024-01-16 at 11 10 41 AM" src="https://github.com/juspay/hyperswitch/assets/55536657/04139f77-8628-4479-8a4d-15cd3f9d9aed">
[ "crates/router/src/connector/cybersource.rs", "crates/router/src/connector/cybersource/transformers.rs", "crates/router/src/services/api.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3387
Bug: [REFACTOR] Add additional field in MandateResponse ### Feature Description Add additional field, `payment_method_response` in MandateResponse ### Possible Implementation Add additional field, `payment_method_response` in MandateResponse ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index d4e11964192..cf25ef195a2 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -131,6 +131,7 @@ host_rs = "" # Rust Locker host mock_locker = true # Emulate a locker locally using Postgres basilisk_host = "" # Basilisk host locker_signing_key_id = "1" # Key_id to sign basilisk hs locker +locker_enabled = true # Boolean to enable or disable saving cards in locker [delayed_session_response] connectors_with_delayed_session_response = "trustpay,payme" # List of connectors which has delayed session response diff --git a/config/development.toml b/config/development.toml index 91269005a0f..b23f68680e6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -69,6 +69,8 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true + [forex_api] call_delay = 21600 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 450fe106a31..8af1528e177 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -56,6 +56,7 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true [jwekey] vault_encryption_key = "" diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 5c0810dc21b..b29f4e0d0c3 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -36,6 +36,8 @@ pub struct MandateResponse { pub payment_method_id: String, /// The payment method pub payment_method: String, + /// The payment method type + pub payment_method_type: Option<String>, /// The card details for mandate pub card: Option<MandateCardDetails>, /// Details about the customer’s acceptance @@ -66,6 +68,15 @@ pub struct MandateCardDetails { #[schema(value_type = Option<String>)] /// A unique identifier alias to identify a particular card pub card_fingerprint: Option<Secret<String>>, + /// The first 6 digits of card + pub card_isin: Option<String>, + /// The bank that issued the card + pub card_issuer: Option<String>, + /// The network that facilitates payment card transactions + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + /// The type of the payment card + pub card_type: Option<String>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 3467777da74..984e6dbffff 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -109,6 +109,19 @@ pub struct CardDetail { /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, + + /// Card Issuing Country + pub card_issuing_country: Option<String>, + + /// Card's Network + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + + /// Issuer Bank for Card + pub card_issuer: Option<String>, + + /// Card Type + pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -177,6 +190,12 @@ pub struct CardDetailsPaymentMethod { pub expiry_year: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_network: Option<api_enums::CardNetwork>, + pub card_type: Option<String>, + #[serde(default = "saved_in_locker_default")] + pub saved_to_locker: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] @@ -227,6 +246,18 @@ pub struct CardDetailFromLocker { #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, + + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_type: Option<String>, + pub saved_to_locker: bool, +} + +fn saved_in_locker_default() -> bool { + true } impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { @@ -242,6 +273,11 @@ impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, + card_isin: item.card_isin, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + saved_to_locker: item.saved_to_locker, } } } @@ -255,6 +291,11 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, + card_isin: item.card_isin, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + saved_to_locker: item.saved_to_locker, } } } diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 42839bf3513..e4a470d0da3 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -54,6 +54,8 @@ impl Default for super::settings::Locker { mock_locker: true, basilisk_host: "localhost".into(), locker_signing_key_id: "1".into(), + //true or false + locker_enabled: true, } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3d93c2f188b..bcf26d63ae8 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -490,6 +490,7 @@ pub struct Locker { pub mock_locker: bool, pub basilisk_host: String, pub locker_signing_key_id: String, + pub locker_enabled: bool, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index e3e308a8a01..4bd2555792a 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -101,6 +101,10 @@ pub async fn call_to_locker( card_exp_year: card.card_exp_year, card_holder_name: card.name_on_card, nick_name: card.nick_name.map(masking::Secret::new), + card_issuing_country: None, + card_network: None, + card_issuer: None, + card_type: None, }; let pm_create = api::PaymentMethodCreate { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index aabd846660c..b6837d14f82 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -33,6 +33,7 @@ use crate::{ pub async fn get_mandate( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateResponse> { let mandate = state @@ -42,7 +43,7 @@ pub async fn get_mandate( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; Ok(services::ApplicationResponse::Json( - mandates::MandateResponse::from_db_mandate(&state, mandate).await?, + mandates::MandateResponse::from_db_mandate(&state, key_store, mandate).await?, )) } @@ -202,6 +203,7 @@ pub async fn update_connector_mandate_id( pub async fn get_customer_mandates( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: customers::CustomerId, ) -> RouterResponse<Vec<mandates::MandateResponse>> { let mandates = state @@ -221,7 +223,10 @@ pub async fn get_customer_mandates( } else { let mut response_vec = Vec::with_capacity(mandates.len()); for mandate in mandates { - response_vec.push(mandates::MandateResponse::from_db_mandate(&state, mandate).await?); + response_vec.push( + mandates::MandateResponse::from_db_mandate(&state, key_store.clone(), mandate) + .await?, + ); } Ok(services::ApplicationResponse::Json(response_vec)) } @@ -383,6 +388,7 @@ where pub async fn retrieve_mandates_list( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, constraints: api_models::mandates::MandateListConstraints, ) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> { let mandates = state @@ -392,11 +398,9 @@ pub async fn retrieve_mandates_list( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve mandates")?; - let mandates_list = future::try_join_all( - mandates - .into_iter() - .map(|mandate| mandates::MandateResponse::from_db_mandate(&state, mandate)), - ) + let mandates_list = future::try_join_all(mandates.into_iter().map(|mandate| { + mandates::MandateResponse::from_db_mandate(&state, key_store.clone(), mandate) + })) .await?; Ok(services::ApplicationResponse::Json(mandates_list)) } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 51f54353635..1a8bbcc8ef7 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -558,6 +558,7 @@ pub async fn add_card_hs( req, &merchant_account.merchant_id, ); + Ok(( payment_method_resp, store_card_payload.duplicate.unwrap_or(false), @@ -2508,11 +2509,19 @@ pub async fn list_customer_payment_method( let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); let (card, pmd, hyperswitch_token_data) = match pm.payment_method { - enums::PaymentMethod::Card => ( - Some(get_card_details(&pm, key, state).await?), - None, - PaymentTokenData::permanent_card(pm.payment_method_id.clone()), - ), + enums::PaymentMethod::Card => { + let card_details = get_card_details_with_locker_fallback(&pm, key, state).await?; + + if card_details.is_some() { + ( + card_details, + None, + PaymentTokenData::permanent_card(pm.payment_method_id.clone()), + ) + } else { + continue; + } + } #[cfg(feature = "payouts")] enums::PaymentMethod::BankTransfer => { @@ -2571,6 +2580,7 @@ pub async fn list_customer_payment_method( }; //Need validation for enabled payment method ,querying MCA + let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), customer_id: pm.customer_id, @@ -2700,7 +2710,38 @@ pub async fn list_customer_payment_method( Ok(services::ApplicationResponse::Json(response)) } -async fn get_card_details( +pub async fn get_card_details_with_locker_fallback( + pm: &payment_method::PaymentMethod, + key: &[u8], + state: &routes::AppState, +) -> errors::RouterResult<Option<api::CardDetailFromLocker>> { + let card_decrypted = + decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("unable to decrypt card details") + .ok() + .flatten() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) + .and_then(|pmd| match pmd { + PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), + _ => None, + }); + + Ok(if let Some(mut crd) = card_decrypted { + if crd.saved_to_locker { + crd.scheme = pm.scheme.clone(); + Some(crd) + } else { + None + } + } else { + Some(get_card_details_from_locker(state, pm).await?) + }) +} + +pub async fn get_card_details_without_locker_fallback( pm: &payment_method::PaymentMethod, key: &[u8], state: &routes::AppState, @@ -2971,25 +3012,32 @@ impl TempLockerCardSupport { pub async fn retrieve_payment_method( state: routes::AppState, pm: api::PaymentMethodId, + key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { let db = state.store.as_ref(); let pm = db .find_payment_method(&pm.payment_method_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + let key = key_store.key.peek(); let card = if pm.payment_method == enums::PaymentMethod::Card { - let card = get_card_from_locker( - &state, - &pm.customer_id, - &pm.merchant_id, - &pm.payment_method_id, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error getting card from card vault")?; - let card_detail = payment_methods::get_card_detail(&pm, card) + let card_detail = if state.conf.locker.locker_enabled { + let card = get_card_from_locker( + &state, + &pm.customer_id, + &pm.merchant_id, + &pm.payment_method_id, + ) + .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while getting card details from locker")?; + .attach_printable("Error getting card from card vault")?; + payment_methods::get_card_detail(&pm, card) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while getting card details from locker")? + } else { + get_card_details_without_locker_fallback(&pm, key, &state).await? + }; Some(card_detail) } else { None diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index da4f03b49c1..304091e42ac 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -352,18 +352,26 @@ pub fn mk_add_card_response_hs( req: api::PaymentMethodCreate, merchant_id: &str, ) -> api::PaymentMethodResponse { - let mut card_number = card.card_number.peek().to_owned(); + let card_number = card.card_number.clone(); + let last4_digits = card_number.clone().get_last4(); + let card_isin = card_number.get_card_isin(); + let card = api::CardDetailFromLocker { scheme: None, - last4_digits: Some(card_number.split_off(card_number.len() - 4)), - issuer_country: None, // [#256] bin mapping - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: None, // [#256] - card_fingerprint: None, // fingerprint not send by basilisk-hs need to have this feature in case we need it in future - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, + last4_digits: Some(last4_digits), + issuer_country: None, + card_number: Some(card.card_number.clone()), + expiry_month: Some(card.card_exp_month.clone()), + expiry_year: Some(card.card_exp_year.clone()), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name.clone(), + nick_name: card.nick_name.clone(), + card_isin: Some(card_isin), + card_issuer: card.card_issuer, + card_network: card.card_network, + card_type: card.card_type, + saved_to_locker: true, }; api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), @@ -399,6 +407,11 @@ pub fn mk_add_card_response( card_fingerprint: Some(response.card_fingerprint), card_holder_name: card.card_holder_name, nick_name: card.nick_name, + card_isin: None, + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, }; api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), @@ -597,6 +610,8 @@ pub fn get_card_detail( ) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> { let card_number = response.card_number; let mut last4_digits = card_number.peek().to_owned(); + //fetch form card bin + let card_detail = api::CardDetailFromLocker { scheme: pm.scheme.to_owned(), issuer_country: pm.issuer_country.clone(), @@ -608,6 +623,11 @@ pub fn get_card_detail( card_fingerprint: None, card_holder_name: response.name_on_card, nick_name: response.nick_name.map(masking::Secret::new), + card_isin: None, + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, }; Ok(card_detail) } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 07af15a336d..15c79f4b9d9 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -92,7 +92,9 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics - if resp.request.setup_mandate_details.clone().is_some() { + let is_mandate = resp.request.setup_mandate_details.is_some(); + + if is_mandate { let payment_method_id = Box::pin(tokenization::save_payment_method( state, connector, diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 0c03c8ce123..d6343ed871b 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -208,6 +208,7 @@ impl types::SetupMandateRouterData { .to_setup_mandate_failed_response()?; let payment_method_type = self.request.payment_method_type; + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 92dc1bf5f4b..e3a3ccdc02c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -509,16 +509,23 @@ pub async fn get_token_for_recurring_mandate( }; if let diesel_models::enums::PaymentMethod::Card = payment_method.payment_method { - let _ = - cards::get_lookup_key_from_locker(state, &token, &payment_method, merchant_key_store) - .await?; + if state.conf.locker.locker_enabled { + let _ = cards::get_lookup_key_from_locker( + state, + &token, + &payment_method, + merchant_key_store, + ) + .await?; + } + if let Some(payment_method_from_request) = req.payment_method { let pm: storage_enums::PaymentMethod = payment_method_from_request; if pm != payment_method.payment_method { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "payment method in request does not match previously provided payment \ - method information" + method information" .into() }))? } @@ -971,7 +978,6 @@ pub fn payment_intent_status_fsm( None => storage_enums::IntentStatus::RequiresPaymentMethod, } } - pub async fn add_domain_task_to_pt<Op>( operation: &Op, state: &AppState, @@ -1034,6 +1040,10 @@ pub(crate) async fn get_payment_method_create_request( card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), + card_issuing_country: card.card_issuing_country.clone(), + card_network: card.card_network.clone(), + card_issuer: card.card_issuer.clone(), + card_type: card.card_type.clone(), }; let customer_id = customer.customer_id.clone(); let payment_method_request = api::PaymentMethodCreate { @@ -3343,21 +3353,23 @@ pub async fn get_additional_payment_data( }, )) }); - card_info.unwrap_or(api_models::payments::AdditionalPaymentData::Card(Box::new( - api_models::payments::AdditionalCardInfo { - card_issuer: None, - card_network: None, - bank_code: None, - card_type: None, - card_issuing_country: None, - last4, - card_isin, - card_extended_bin, - card_exp_month: Some(card_data.card_exp_month.clone()), - card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: card_data.card_holder_name.clone(), - }, - ))) + card_info.unwrap_or_else(|| { + api_models::payments::AdditionalPaymentData::Card(Box::new( + api_models::payments::AdditionalCardInfo { + card_issuer: None, + card_network: None, + bank_code: None, + card_type: None, + card_issuing_country: None, + last4, + card_isin, + card_extended_bin, + card_exp_month: Some(card_data.card_exp_month.clone()), + card_exp_year: Some(card_data.card_exp_year.clone()), + card_holder_name: card_data.card_holder_name.clone(), + }, + )) + }) } } api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => { diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index f884cb79e7e..15d88c94660 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -14,7 +14,7 @@ use crate::{ services, types::{ self, - api::{self, CardDetailsPaymentMethod, PaymentMethodCreateExt}, + api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, storage::enums as storage_enums, }, @@ -74,12 +74,21 @@ where .await?; let merchant_id = &merchant_account.merchant_id; - let locker_response = save_in_locker( - state, - merchant_account, - payment_method_create_request.to_owned(), - ) - .await?; + let locker_response = if !state.conf.locker.locker_enabled { + skip_saving_card_in_locker( + merchant_account, + payment_method_create_request.to_owned(), + ) + .await? + } else { + save_in_locker( + state, + merchant_account, + payment_method_create_request.to_owned(), + ) + .await? + }; + let is_duplicate = locker_response.1; let pm_card_details = locker_response.0.card.as_ref().map(|card| { @@ -168,6 +177,85 @@ where } } +async fn skip_saving_card_in_locker( + merchant_account: &domain::MerchantAccount, + payment_method_request: api::PaymentMethodCreate, +) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { + let merchant_id = &merchant_account.merchant_id; + let customer_id = payment_method_request + .clone() + .customer_id + .clone() + .get_required_value("customer_id")?; + let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + + let last4_digits = payment_method_request + .card + .clone() + .map(|c| c.card_number.get_last4()); + + let card_isin = payment_method_request + .card + .clone() + .map(|c: api_models::payment_methods::CardDetail| c.card_number.get_card_isin()); + + match payment_method_request.card.clone() { + Some(card) => { + let card_detail = CardDetailFromLocker { + scheme: None, + issuer_country: card.card_issuing_country.clone(), + last4_digits: last4_digits.clone(), + card_number: None, + expiry_month: Some(card.card_exp_month.clone()), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_holder_name: card.card_holder_name.clone(), + card_fingerprint: None, + nick_name: None, + card_isin: card_isin.clone(), + card_issuer: card.card_issuer.clone(), + card_network: card.card_network.clone(), + card_type: card.card_type.clone(), + saved_to_locker: false, + }; + let pm_resp = api::PaymentMethodResponse { + merchant_id: merchant_id.to_string(), + customer_id: Some(customer_id), + payment_method_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: Some(card_detail), + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + metadata: None, + created: Some(common_utils::date_time::now()), + bank_transfer: None, + }; + + Ok((pm_resp, false)) + } + None => { + let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + let payment_method_response = api::PaymentMethodResponse { + merchant_id: merchant_id.to_string(), + customer_id: Some(customer_id), + payment_method_id: pm_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: None, + metadata: None, + created: Some(common_utils::date_time::now()), + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + bank_transfer: None, + }; + Ok((payment_method_response, false)) + } + } +} + pub async fn save_in_locker( state: &AppState, merchant_account: &domain::MerchantAccount, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 56e3a6faf53..1ab24023bdb 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1,6 +1,6 @@ use common_utils::{ errors::CustomResult, - ext_traits::{StringExt, ValueExt}, + ext_traits::{AsyncExt, StringExt, ValueExt}, }; use diesel_models::encryption::Encryption; use error_stack::{IntoReport, ResultExt}; @@ -19,6 +19,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api::{self, enums as api_enums}, domain::{ @@ -184,6 +185,10 @@ pub async fn save_payout_data_to_locker( card_exp_month: card.expiry_month.to_owned(), card_exp_year: card.expiry_year.to_owned(), nick_name: None, + card_issuing_country: None, + card_network: None, + card_issuer: None, + card_type: None, }; let payload = StoreLockerReq::LockerCard(StoreCardReq { merchant_id: &merchant_account.merchant_id, @@ -267,20 +272,65 @@ pub async fn save_payout_data_to_locker( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in saved payout method")?; - let pm_data = api::payment_methods::PaymentMethodsData::Card( - api::payment_methods::CardDetailsPaymentMethod { - last4_digits: card_details - .as_ref() - .map(|c| c.card_number.clone().get_last4()), - issuer_country: None, - expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), - expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), - nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), - card_holder_name: card_details - .as_ref() - .and_then(|c| c.card_holder_name.clone()), - }, - ); + // fetch card info from db + let card_isin = card_details + .as_ref() + .map(|c| c.card_number.clone().get_card_isin()); + + let pm_data = card_isin + .clone() + .async_and_then(|card_isin| async move { + db.get_card_info(&card_isin) + .await + .map_err(|error| services::logger::warn!(card_info_error=?error)) + .ok() + }) + .await + .flatten() + .map(|card_info| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: card_info.card_issuing_country, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: card_info.card_issuer, + card_network: card_info.card_network, + card_type: card_info.card_type, + saved_to_locker: true, + }, + ) + }) + .unwrap_or_else(|| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: None, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, + }, + ) + }); let card_details_encrypted = cards::create_encrypted_payment_method_data(key_store, Some(pm_data)).await; diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 4354a3ee195..f291d1cd2e8 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -421,6 +421,7 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: api_models::webhooks::IncomingWebhookEvent, @@ -464,8 +465,12 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let mandates_response = Box::new( - api::mandates::MandateResponse::from_db_mandate(&state, updated_mandate.clone()) - .await?, + api::mandates::MandateResponse::from_db_mandate( + &state, + key_store, + updated_mandate.clone(), + ) + .await?, ); let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); if let Some(outgoing_event_type) = event_type { @@ -1237,6 +1242,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr state.clone(), merchant_account, business_profile, + key_store, webhook_details, source_verified, event_type, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 2592d8837d5..e7a0804500c 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -226,7 +226,12 @@ pub async fn get_customer_mandates( &req, customer_id, |state, auth, req| { - crate::core::mandate::get_customer_mandates(state, auth.merchant_account, req) + crate::core::mandate::get_customer_mandates( + state, + auth.merchant_account, + auth.key_store, + req, + ) }, auth::auth_type( &auth::ApiKeyAuth, diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index ecc89a10fa2..468d202b94c 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -41,7 +41,7 @@ pub async fn get_mandate( state, &req, mandate_id, - |state, auth, req| mandate::get_mandate(state, auth.merchant_account, req), + |state, auth, req| mandate::get_mandate(state, auth.merchant_account, auth.key_store, req), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) @@ -123,7 +123,9 @@ pub async fn retrieve_mandates_list( state, &req, payload, - |state, auth, req| mandate::retrieve_mandates_list(state, auth.merchant_account, req), + |state, auth, req| { + mandate::retrieve_mandates_list(state, auth.merchant_account, auth.key_store, req) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::MandateRead), diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index a6eeeabd687..6ef5de886be 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -242,7 +242,7 @@ pub async fn payment_method_retrieve_api( state, &req, payload, - |state, _auth, pm| cards::retrieve_payment_method(state, pm), + |state, auth, pm| cards::retrieve_payment_method(state, pm, auth.key_store), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 8d6b9a15e3a..f6b2d7bba93 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -1,6 +1,7 @@ use api_models::mandates; pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse}; use error_stack::ResultExt; +use masking::PeekInterface; use serde::{Deserialize, Serialize}; use crate::{ @@ -11,7 +12,7 @@ use crate::{ newtype, routes::AppState, types::{ - api, + api, domain, storage::{self, enums as storage_enums}, }, }; @@ -23,12 +24,20 @@ newtype!( #[async_trait::async_trait] pub(crate) trait MandateResponseExt: Sized { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self>; + async fn from_db_mandate( + state: &AppState, + key_store: domain::MerchantKeyStore, + mandate: storage::Mandate, + ) -> RouterResult<Self>; } #[async_trait::async_trait] impl MandateResponseExt for MandateResponse { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self> { + async fn from_db_mandate( + state: &AppState, + key_store: domain::MerchantKeyStore, + mandate: storage::Mandate, + ) -> RouterResult<Self> { let db = &*state.store; let payment_method = db .find_payment_method(&mandate.payment_method_id) @@ -36,21 +45,35 @@ impl MandateResponseExt for MandateResponse { .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let card = if payment_method.payment_method == storage_enums::PaymentMethod::Card { - let card = payment_methods::cards::get_card_from_locker( - state, - &payment_method.customer_id, - &payment_method.merchant_id, - &payment_method.payment_method_id, - ) - .await?; - let card_detail = payment_methods::transformers::get_card_detail(&payment_method, card) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while getting card details")?; - Some(MandateCardDetails::from(card_detail).into_inner()) + // if locker is disabled , decrypt the payment method data + let card_details = if state.conf.locker.locker_enabled { + let card = payment_methods::cards::get_card_from_locker( + state, + &payment_method.customer_id, + &payment_method.merchant_id, + &payment_method.payment_method_id, + ) + .await?; + + payment_methods::transformers::get_card_detail(&payment_method, card) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while getting card details")? + } else { + payment_methods::cards::get_card_details_without_locker_fallback( + &payment_method, + key_store.key.get_inner().peek(), + state, + ) + .await? + }; + + Some(MandateCardDetails::from(card_details).into_inner()) } else { None }; - + let payment_method_type = payment_method + .payment_method_type + .map(|pmt| pmt.to_string()); Ok(Self { mandate_id: mandate.mandate_id, customer_acceptance: Some(api::payments::CustomerAcceptance { @@ -68,6 +91,7 @@ impl MandateResponseExt for MandateResponse { card, status: mandate.mandate_status, payment_method: payment_method.payment_method.to_string(), + payment_method_type, payment_method_id: mandate.payment_method_id, }) } @@ -84,6 +108,10 @@ impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { scheme: card_details_from_locker.scheme, issuer_country: card_details_from_locker.issuer_country, card_fingerprint: card_details_from_locker.card_fingerprint, + card_isin: card_details_from_locker.card_isin, + card_issuer: card_details_from_locker.card_issuer, + card_network: card_details_from_locker.card_network, + card_type: card_details_from_locker.card_type, } .into() } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 358a591a667..268ebd1d3ac 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -33,6 +33,7 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true [forex_api] call_delay = 21600 diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index b2f5d3ea52c..02df6324a06 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4421,11 +4421,37 @@ "description": "Card Holder's Nick Name", "example": "John Doe", "nullable": true + }, + "card_issuing_country": { + "type": "string", + "description": "Card Issuing Country", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_issuer": { + "type": "string", + "description": "Issuer Bank for Card", + "nullable": true + }, + "card_type": { + "type": "string", + "description": "Card Type", + "nullable": true } } }, "CardDetailFromLocker": { "type": "object", + "required": [ + "saved_to_locker" + ], "properties": { "scheme": { "type": "string", @@ -4462,6 +4488,29 @@ "nick_name": { "type": "string", "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_isin": { + "type": "string", + "nullable": true + }, + "card_issuer": { + "type": "string", + "nullable": true + }, + "card_type": { + "type": "string", + "nullable": true + }, + "saved_to_locker": { + "type": "boolean" } } }, @@ -6884,6 +6933,29 @@ "type": "string", "description": "A unique identifier alias to identify a particular card", "nullable": true + }, + "card_isin": { + "type": "string", + "description": "The first 6 digits of card", + "nullable": true + }, + "card_issuer": { + "type": "string", + "description": "The bank that issued the card", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_type": { + "type": "string", + "description": "The type of the payment card", + "nullable": true } } }, @@ -6932,6 +7004,11 @@ "type": "string", "description": "The payment method" }, + "payment_method_type": { + "type": "string", + "description": "The payment method type", + "nullable": true + }, "card": { "allOf": [ {
2024-01-15T11:31:45Z
## Description Add locker config to enable or disable locker , so that if the locker is enabled we can store the card_details in the locker else if the config is disabled we don't Also this PR involvesaddition in the `MandateResponse`. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This Feature provides an option for the merchant whether or not to save the card at hyperswitch . Saving the card at hyperswitch is not necessary if the mandate is created at the processor level. #
2f693ad1fd857280ef30c6cc0297fb926f0e79e8
- Create an MA & MCA - Disable the `locker_enabled` config > Create a Mandate payment , the details will not be stored in Locker and payment will be successful > List PaymentMethods for a Customer won't have any details as the card was never stored > List the Mandates would have mandate details ![Screenshot 2024-01-16 at 4 38 43 PM](https://github.com/juspay/hyperswitch/assets/55580080/c9d5d11b-b31f-4a58-a324-f92c376a7c26) ![Screenshot 2024-01-16 at 4 38 59 PM](https://github.com/juspay/hyperswitch/assets/55580080/32645dfa-c962-43a2-9e7f-ca1056415560) ![Screenshot 2024-01-16 at 4 39 10 PM](https://github.com/juspay/hyperswitch/assets/55580080/f413bd94-b74c-4a1b-bf22-fbc335a05e56) ![Screenshot 2024-01-16 at 4 39 26 PM](https://github.com/juspay/hyperswitch/assets/55580080/2745fabd-bc81-4d2b-ab53-d6829fa53d13) ![Screenshot 2024-01-16 at 4 39 38 PM](https://github.com/juspay/hyperswitch/assets/55580080/25221f1c-7932-4295-9a6e-083355513c15) - Enable the `locker_enabled` config > Create a Mandate payment , the details will be stored in Locker and payment will be successful > List PaymentMethods for a Customer would have details of the card that was stored > List the Mandates ![Screenshot 2024-01-16 at 4 33 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/174a1933-9112-4088-893c-12c4e84b3148) ![Screenshot 2024-01-16 at 4 34 57 PM](https://github.com/juspay/hyperswitch/assets/55580080/2a5f46e7-86b0-470e-89a6-3a8f0a225c3b) ![Screenshot 2024-01-16 at 4 35 18 PM](https://github.com/juspay/hyperswitch/assets/55580080/66a1df1f-0f8a-418e-a122-570508eb97a9) ![Screenshot 2024-01-16 at 4 35 33 PM](https://github.com/juspay/hyperswitch/assets/55580080/8c5fe598-9cad-498f-88eb-ef9ca0c3018b) ![Screenshot 2024-01-16 at 4 35 51 PM](https://github.com/juspay/hyperswitch/assets/55580080/8d05dbcb-ef2d-4c2a-b326-56393ed5b16e) ![Screenshot 2024-01-16 at 4 36 32 PM](https://github.com/juspay/hyperswitch/assets/55580080/0e3e9272-27b5-44de-9c3a-4e1e942faee9) -When we do a list mandates we have an additional field `payment_method_type` ![Screenshot 2024-01-18 at 4 27 53 PM](https://github.com/juspay/hyperswitch/assets/55580080/7b2455e7-889b-4e01-979d-56353ce60f49)
[ "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/mandates.rs", "crates/api_models/src/payment_methods.rs", "crates/router/src/configs/defaults.rs", "crates/router/src/configs/settings.rs", "crates/router/src/core/locker_migration.rs", "cra...
juspay/hyperswitch
juspay__hyperswitch-3361
Bug: [REFACTOR] Add config to enable and disable locker ### Feature Description Add config to disable or enable locker. If the config is set as false then we don't store the card_details in locker else we store the details in the locker. ### Possible Implementation While a payment gets created, make a decision based on the config to either save or not save in the locker. When the locker has been disabled, no cards are saved hence no payment_token is generated for that payment and while listing the mandates we shouldn't make a call to the locker, we should be able to decrypt the value in `payment_method_data` field and give back the details. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index d4e11964192..cf25ef195a2 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -131,6 +131,7 @@ host_rs = "" # Rust Locker host mock_locker = true # Emulate a locker locally using Postgres basilisk_host = "" # Basilisk host locker_signing_key_id = "1" # Key_id to sign basilisk hs locker +locker_enabled = true # Boolean to enable or disable saving cards in locker [delayed_session_response] connectors_with_delayed_session_response = "trustpay,payme" # List of connectors which has delayed session response diff --git a/config/development.toml b/config/development.toml index 91269005a0f..b23f68680e6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -69,6 +69,8 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true + [forex_api] call_delay = 21600 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 450fe106a31..8af1528e177 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -56,6 +56,7 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true [jwekey] vault_encryption_key = "" diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 5c0810dc21b..b29f4e0d0c3 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -36,6 +36,8 @@ pub struct MandateResponse { pub payment_method_id: String, /// The payment method pub payment_method: String, + /// The payment method type + pub payment_method_type: Option<String>, /// The card details for mandate pub card: Option<MandateCardDetails>, /// Details about the customer’s acceptance @@ -66,6 +68,15 @@ pub struct MandateCardDetails { #[schema(value_type = Option<String>)] /// A unique identifier alias to identify a particular card pub card_fingerprint: Option<Secret<String>>, + /// The first 6 digits of card + pub card_isin: Option<String>, + /// The bank that issued the card + pub card_issuer: Option<String>, + /// The network that facilitates payment card transactions + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + /// The type of the payment card + pub card_type: Option<String>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 3467777da74..984e6dbffff 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -109,6 +109,19 @@ pub struct CardDetail { /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, + + /// Card Issuing Country + pub card_issuing_country: Option<String>, + + /// Card's Network + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + + /// Issuer Bank for Card + pub card_issuer: Option<String>, + + /// Card Type + pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -177,6 +190,12 @@ pub struct CardDetailsPaymentMethod { pub expiry_year: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_network: Option<api_enums::CardNetwork>, + pub card_type: Option<String>, + #[serde(default = "saved_in_locker_default")] + pub saved_to_locker: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] @@ -227,6 +246,18 @@ pub struct CardDetailFromLocker { #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, + + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + + pub card_isin: Option<String>, + pub card_issuer: Option<String>, + pub card_type: Option<String>, + pub saved_to_locker: bool, +} + +fn saved_in_locker_default() -> bool { + true } impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { @@ -242,6 +273,11 @@ impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, + card_isin: item.card_isin, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + saved_to_locker: item.saved_to_locker, } } } @@ -255,6 +291,11 @@ impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, + card_isin: item.card_isin, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + saved_to_locker: item.saved_to_locker, } } } diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 42839bf3513..e4a470d0da3 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -54,6 +54,8 @@ impl Default for super::settings::Locker { mock_locker: true, basilisk_host: "localhost".into(), locker_signing_key_id: "1".into(), + //true or false + locker_enabled: true, } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3d93c2f188b..bcf26d63ae8 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -490,6 +490,7 @@ pub struct Locker { pub mock_locker: bool, pub basilisk_host: String, pub locker_signing_key_id: String, + pub locker_enabled: bool, } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs index e3e308a8a01..4bd2555792a 100644 --- a/crates/router/src/core/locker_migration.rs +++ b/crates/router/src/core/locker_migration.rs @@ -101,6 +101,10 @@ pub async fn call_to_locker( card_exp_year: card.card_exp_year, card_holder_name: card.name_on_card, nick_name: card.nick_name.map(masking::Secret::new), + card_issuing_country: None, + card_network: None, + card_issuer: None, + card_type: None, }; let pm_create = api::PaymentMethodCreate { diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index aabd846660c..b6837d14f82 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -33,6 +33,7 @@ use crate::{ pub async fn get_mandate( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateResponse> { let mandate = state @@ -42,7 +43,7 @@ pub async fn get_mandate( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; Ok(services::ApplicationResponse::Json( - mandates::MandateResponse::from_db_mandate(&state, mandate).await?, + mandates::MandateResponse::from_db_mandate(&state, key_store, mandate).await?, )) } @@ -202,6 +203,7 @@ pub async fn update_connector_mandate_id( pub async fn get_customer_mandates( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: customers::CustomerId, ) -> RouterResponse<Vec<mandates::MandateResponse>> { let mandates = state @@ -221,7 +223,10 @@ pub async fn get_customer_mandates( } else { let mut response_vec = Vec::with_capacity(mandates.len()); for mandate in mandates { - response_vec.push(mandates::MandateResponse::from_db_mandate(&state, mandate).await?); + response_vec.push( + mandates::MandateResponse::from_db_mandate(&state, key_store.clone(), mandate) + .await?, + ); } Ok(services::ApplicationResponse::Json(response_vec)) } @@ -383,6 +388,7 @@ where pub async fn retrieve_mandates_list( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, constraints: api_models::mandates::MandateListConstraints, ) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> { let mandates = state @@ -392,11 +398,9 @@ pub async fn retrieve_mandates_list( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to retrieve mandates")?; - let mandates_list = future::try_join_all( - mandates - .into_iter() - .map(|mandate| mandates::MandateResponse::from_db_mandate(&state, mandate)), - ) + let mandates_list = future::try_join_all(mandates.into_iter().map(|mandate| { + mandates::MandateResponse::from_db_mandate(&state, key_store.clone(), mandate) + })) .await?; Ok(services::ApplicationResponse::Json(mandates_list)) } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 51f54353635..1a8bbcc8ef7 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -558,6 +558,7 @@ pub async fn add_card_hs( req, &merchant_account.merchant_id, ); + Ok(( payment_method_resp, store_card_payload.duplicate.unwrap_or(false), @@ -2508,11 +2509,19 @@ pub async fn list_customer_payment_method( let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token"); let (card, pmd, hyperswitch_token_data) = match pm.payment_method { - enums::PaymentMethod::Card => ( - Some(get_card_details(&pm, key, state).await?), - None, - PaymentTokenData::permanent_card(pm.payment_method_id.clone()), - ), + enums::PaymentMethod::Card => { + let card_details = get_card_details_with_locker_fallback(&pm, key, state).await?; + + if card_details.is_some() { + ( + card_details, + None, + PaymentTokenData::permanent_card(pm.payment_method_id.clone()), + ) + } else { + continue; + } + } #[cfg(feature = "payouts")] enums::PaymentMethod::BankTransfer => { @@ -2571,6 +2580,7 @@ pub async fn list_customer_payment_method( }; //Need validation for enabled payment method ,querying MCA + let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), customer_id: pm.customer_id, @@ -2700,7 +2710,38 @@ pub async fn list_customer_payment_method( Ok(services::ApplicationResponse::Json(response)) } -async fn get_card_details( +pub async fn get_card_details_with_locker_fallback( + pm: &payment_method::PaymentMethod, + key: &[u8], + state: &routes::AppState, +) -> errors::RouterResult<Option<api::CardDetailFromLocker>> { + let card_decrypted = + decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("unable to decrypt card details") + .ok() + .flatten() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) + .and_then(|pmd| match pmd { + PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), + _ => None, + }); + + Ok(if let Some(mut crd) = card_decrypted { + if crd.saved_to_locker { + crd.scheme = pm.scheme.clone(); + Some(crd) + } else { + None + } + } else { + Some(get_card_details_from_locker(state, pm).await?) + }) +} + +pub async fn get_card_details_without_locker_fallback( pm: &payment_method::PaymentMethod, key: &[u8], state: &routes::AppState, @@ -2971,25 +3012,32 @@ impl TempLockerCardSupport { pub async fn retrieve_payment_method( state: routes::AppState, pm: api::PaymentMethodId, + key_store: domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { let db = state.store.as_ref(); let pm = db .find_payment_method(&pm.payment_method_id) .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + let key = key_store.key.peek(); let card = if pm.payment_method == enums::PaymentMethod::Card { - let card = get_card_from_locker( - &state, - &pm.customer_id, - &pm.merchant_id, - &pm.payment_method_id, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error getting card from card vault")?; - let card_detail = payment_methods::get_card_detail(&pm, card) + let card_detail = if state.conf.locker.locker_enabled { + let card = get_card_from_locker( + &state, + &pm.customer_id, + &pm.merchant_id, + &pm.payment_method_id, + ) + .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while getting card details from locker")?; + .attach_printable("Error getting card from card vault")?; + payment_methods::get_card_detail(&pm, card) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while getting card details from locker")? + } else { + get_card_details_without_locker_fallback(&pm, key, &state).await? + }; Some(card_detail) } else { None diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index da4f03b49c1..304091e42ac 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -352,18 +352,26 @@ pub fn mk_add_card_response_hs( req: api::PaymentMethodCreate, merchant_id: &str, ) -> api::PaymentMethodResponse { - let mut card_number = card.card_number.peek().to_owned(); + let card_number = card.card_number.clone(); + let last4_digits = card_number.clone().get_last4(); + let card_isin = card_number.get_card_isin(); + let card = api::CardDetailFromLocker { scheme: None, - last4_digits: Some(card_number.split_off(card_number.len() - 4)), - issuer_country: None, // [#256] bin mapping - card_number: Some(card.card_number), - expiry_month: Some(card.card_exp_month), - expiry_year: Some(card.card_exp_year), - card_token: None, // [#256] - card_fingerprint: None, // fingerprint not send by basilisk-hs need to have this feature in case we need it in future - card_holder_name: card.card_holder_name, - nick_name: card.nick_name, + last4_digits: Some(last4_digits), + issuer_country: None, + card_number: Some(card.card_number.clone()), + expiry_month: Some(card.card_exp_month.clone()), + expiry_year: Some(card.card_exp_year.clone()), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name.clone(), + nick_name: card.nick_name.clone(), + card_isin: Some(card_isin), + card_issuer: card.card_issuer, + card_network: card.card_network, + card_type: card.card_type, + saved_to_locker: true, }; api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), @@ -399,6 +407,11 @@ pub fn mk_add_card_response( card_fingerprint: Some(response.card_fingerprint), card_holder_name: card.card_holder_name, nick_name: card.nick_name, + card_isin: None, + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, }; api::PaymentMethodResponse { merchant_id: merchant_id.to_owned(), @@ -597,6 +610,8 @@ pub fn get_card_detail( ) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> { let card_number = response.card_number; let mut last4_digits = card_number.peek().to_owned(); + //fetch form card bin + let card_detail = api::CardDetailFromLocker { scheme: pm.scheme.to_owned(), issuer_country: pm.issuer_country.clone(), @@ -608,6 +623,11 @@ pub fn get_card_detail( card_fingerprint: None, card_holder_name: response.name_on_card, nick_name: response.nick_name.map(masking::Secret::new), + card_isin: None, + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, }; Ok(card_detail) } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 07af15a336d..15c79f4b9d9 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -92,7 +92,9 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics - if resp.request.setup_mandate_details.clone().is_some() { + let is_mandate = resp.request.setup_mandate_details.is_some(); + + if is_mandate { let payment_method_id = Box::pin(tokenization::save_payment_method( state, connector, diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index 0c03c8ce123..d6343ed871b 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -208,6 +208,7 @@ impl types::SetupMandateRouterData { .to_setup_mandate_failed_response()?; let payment_method_type = self.request.payment_method_type; + let pm_id = Box::pin(tokenization::save_payment_method( state, connector, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 92dc1bf5f4b..e3a3ccdc02c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -509,16 +509,23 @@ pub async fn get_token_for_recurring_mandate( }; if let diesel_models::enums::PaymentMethod::Card = payment_method.payment_method { - let _ = - cards::get_lookup_key_from_locker(state, &token, &payment_method, merchant_key_store) - .await?; + if state.conf.locker.locker_enabled { + let _ = cards::get_lookup_key_from_locker( + state, + &token, + &payment_method, + merchant_key_store, + ) + .await?; + } + if let Some(payment_method_from_request) = req.payment_method { let pm: storage_enums::PaymentMethod = payment_method_from_request; if pm != payment_method.payment_method { Err(report!(errors::ApiErrorResponse::PreconditionFailed { message: "payment method in request does not match previously provided payment \ - method information" + method information" .into() }))? } @@ -971,7 +978,6 @@ pub fn payment_intent_status_fsm( None => storage_enums::IntentStatus::RequiresPaymentMethod, } } - pub async fn add_domain_task_to_pt<Op>( operation: &Op, state: &AppState, @@ -1034,6 +1040,10 @@ pub(crate) async fn get_payment_method_create_request( card_exp_year: card.card_exp_year.clone(), card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), + card_issuing_country: card.card_issuing_country.clone(), + card_network: card.card_network.clone(), + card_issuer: card.card_issuer.clone(), + card_type: card.card_type.clone(), }; let customer_id = customer.customer_id.clone(); let payment_method_request = api::PaymentMethodCreate { @@ -3343,21 +3353,23 @@ pub async fn get_additional_payment_data( }, )) }); - card_info.unwrap_or(api_models::payments::AdditionalPaymentData::Card(Box::new( - api_models::payments::AdditionalCardInfo { - card_issuer: None, - card_network: None, - bank_code: None, - card_type: None, - card_issuing_country: None, - last4, - card_isin, - card_extended_bin, - card_exp_month: Some(card_data.card_exp_month.clone()), - card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: card_data.card_holder_name.clone(), - }, - ))) + card_info.unwrap_or_else(|| { + api_models::payments::AdditionalPaymentData::Card(Box::new( + api_models::payments::AdditionalCardInfo { + card_issuer: None, + card_network: None, + bank_code: None, + card_type: None, + card_issuing_country: None, + last4, + card_isin, + card_extended_bin, + card_exp_month: Some(card_data.card_exp_month.clone()), + card_exp_year: Some(card_data.card_exp_year.clone()), + card_holder_name: card_data.card_holder_name.clone(), + }, + )) + }) } } api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => { diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index f884cb79e7e..15d88c94660 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -14,7 +14,7 @@ use crate::{ services, types::{ self, - api::{self, CardDetailsPaymentMethod, PaymentMethodCreateExt}, + api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, storage::enums as storage_enums, }, @@ -74,12 +74,21 @@ where .await?; let merchant_id = &merchant_account.merchant_id; - let locker_response = save_in_locker( - state, - merchant_account, - payment_method_create_request.to_owned(), - ) - .await?; + let locker_response = if !state.conf.locker.locker_enabled { + skip_saving_card_in_locker( + merchant_account, + payment_method_create_request.to_owned(), + ) + .await? + } else { + save_in_locker( + state, + merchant_account, + payment_method_create_request.to_owned(), + ) + .await? + }; + let is_duplicate = locker_response.1; let pm_card_details = locker_response.0.card.as_ref().map(|card| { @@ -168,6 +177,85 @@ where } } +async fn skip_saving_card_in_locker( + merchant_account: &domain::MerchantAccount, + payment_method_request: api::PaymentMethodCreate, +) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { + let merchant_id = &merchant_account.merchant_id; + let customer_id = payment_method_request + .clone() + .customer_id + .clone() + .get_required_value("customer_id")?; + let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + + let last4_digits = payment_method_request + .card + .clone() + .map(|c| c.card_number.get_last4()); + + let card_isin = payment_method_request + .card + .clone() + .map(|c: api_models::payment_methods::CardDetail| c.card_number.get_card_isin()); + + match payment_method_request.card.clone() { + Some(card) => { + let card_detail = CardDetailFromLocker { + scheme: None, + issuer_country: card.card_issuing_country.clone(), + last4_digits: last4_digits.clone(), + card_number: None, + expiry_month: Some(card.card_exp_month.clone()), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_holder_name: card.card_holder_name.clone(), + card_fingerprint: None, + nick_name: None, + card_isin: card_isin.clone(), + card_issuer: card.card_issuer.clone(), + card_network: card.card_network.clone(), + card_type: card.card_type.clone(), + saved_to_locker: false, + }; + let pm_resp = api::PaymentMethodResponse { + merchant_id: merchant_id.to_string(), + customer_id: Some(customer_id), + payment_method_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: Some(card_detail), + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + metadata: None, + created: Some(common_utils::date_time::now()), + bank_transfer: None, + }; + + Ok((pm_resp, false)) + } + None => { + let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); + let payment_method_response = api::PaymentMethodResponse { + merchant_id: merchant_id.to_string(), + customer_id: Some(customer_id), + payment_method_id: pm_id, + payment_method: payment_method_request.payment_method, + payment_method_type: payment_method_request.payment_method_type, + card: None, + metadata: None, + created: Some(common_utils::date_time::now()), + recurring_enabled: false, + installment_payment_enabled: false, + payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), + bank_transfer: None, + }; + Ok((payment_method_response, false)) + } + } +} + pub async fn save_in_locker( state: &AppState, merchant_account: &domain::MerchantAccount, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 56e3a6faf53..1ab24023bdb 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1,6 +1,6 @@ use common_utils::{ errors::CustomResult, - ext_traits::{StringExt, ValueExt}, + ext_traits::{AsyncExt, StringExt, ValueExt}, }; use diesel_models::encryption::Encryption; use error_stack::{IntoReport, ResultExt}; @@ -19,6 +19,7 @@ use crate::{ }, db::StorageInterface, routes::AppState, + services, types::{ api::{self, enums as api_enums}, domain::{ @@ -184,6 +185,10 @@ pub async fn save_payout_data_to_locker( card_exp_month: card.expiry_month.to_owned(), card_exp_year: card.expiry_year.to_owned(), nick_name: None, + card_issuing_country: None, + card_network: None, + card_issuer: None, + card_type: None, }; let payload = StoreLockerReq::LockerCard(StoreCardReq { merchant_id: &merchant_account.merchant_id, @@ -267,20 +272,65 @@ pub async fn save_payout_data_to_locker( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error updating payouts in saved payout method")?; - let pm_data = api::payment_methods::PaymentMethodsData::Card( - api::payment_methods::CardDetailsPaymentMethod { - last4_digits: card_details - .as_ref() - .map(|c| c.card_number.clone().get_last4()), - issuer_country: None, - expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), - expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), - nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), - card_holder_name: card_details - .as_ref() - .and_then(|c| c.card_holder_name.clone()), - }, - ); + // fetch card info from db + let card_isin = card_details + .as_ref() + .map(|c| c.card_number.clone().get_card_isin()); + + let pm_data = card_isin + .clone() + .async_and_then(|card_isin| async move { + db.get_card_info(&card_isin) + .await + .map_err(|error| services::logger::warn!(card_info_error=?error)) + .ok() + }) + .await + .flatten() + .map(|card_info| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: card_info.card_issuing_country, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: card_info.card_issuer, + card_network: card_info.card_network, + card_type: card_info.card_type, + saved_to_locker: true, + }, + ) + }) + .unwrap_or_else(|| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod { + last4_digits: card_details + .as_ref() + .map(|c| c.card_number.clone().get_last4()), + issuer_country: None, + expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()), + expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()), + nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()), + card_holder_name: card_details + .as_ref() + .and_then(|c| c.card_holder_name.clone()), + + card_isin: card_isin.clone(), + card_issuer: None, + card_network: None, + card_type: None, + saved_to_locker: true, + }, + ) + }); let card_details_encrypted = cards::create_encrypted_payment_method_data(key_store, Some(pm_data)).await; diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 4354a3ee195..f291d1cd2e8 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -421,6 +421,7 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( state: AppState, merchant_account: domain::MerchantAccount, business_profile: diesel_models::business_profile::BusinessProfile, + key_store: domain::MerchantKeyStore, webhook_details: api::IncomingWebhookDetails, source_verified: bool, event_type: api_models::webhooks::IncomingWebhookEvent, @@ -464,8 +465,12 @@ pub async fn mandates_incoming_webhook_flow<W: types::OutgoingWebhookType>( .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; let mandates_response = Box::new( - api::mandates::MandateResponse::from_db_mandate(&state, updated_mandate.clone()) - .await?, + api::mandates::MandateResponse::from_db_mandate( + &state, + key_store, + updated_mandate.clone(), + ) + .await?, ); let event_type: Option<enums::EventType> = updated_mandate.mandate_status.foreign_into(); if let Some(outgoing_event_type) = event_type { @@ -1237,6 +1242,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr state.clone(), merchant_account, business_profile, + key_store, webhook_details, source_verified, event_type, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 2592d8837d5..e7a0804500c 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -226,7 +226,12 @@ pub async fn get_customer_mandates( &req, customer_id, |state, auth, req| { - crate::core::mandate::get_customer_mandates(state, auth.merchant_account, req) + crate::core::mandate::get_customer_mandates( + state, + auth.merchant_account, + auth.key_store, + req, + ) }, auth::auth_type( &auth::ApiKeyAuth, diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index ecc89a10fa2..468d202b94c 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -41,7 +41,7 @@ pub async fn get_mandate( state, &req, mandate_id, - |state, auth, req| mandate::get_mandate(state, auth.merchant_account, req), + |state, auth, req| mandate::get_mandate(state, auth.merchant_account, auth.key_store, req), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) @@ -123,7 +123,9 @@ pub async fn retrieve_mandates_list( state, &req, payload, - |state, auth, req| mandate::retrieve_mandates_list(state, auth.merchant_account, req), + |state, auth, req| { + mandate::retrieve_mandates_list(state, auth.merchant_account, auth.key_store, req) + }, auth::auth_type( &auth::ApiKeyAuth, &auth::JWTAuth(Permission::MandateRead), diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index a6eeeabd687..6ef5de886be 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -242,7 +242,7 @@ pub async fn payment_method_retrieve_api( state, &req, payload, - |state, _auth, pm| cards::retrieve_payment_method(state, pm), + |state, auth, pm| cards::retrieve_payment_method(state, pm, auth.key_store), &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs index 8d6b9a15e3a..f6b2d7bba93 100644 --- a/crates/router/src/types/api/mandates.rs +++ b/crates/router/src/types/api/mandates.rs @@ -1,6 +1,7 @@ use api_models::mandates; pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse}; use error_stack::ResultExt; +use masking::PeekInterface; use serde::{Deserialize, Serialize}; use crate::{ @@ -11,7 +12,7 @@ use crate::{ newtype, routes::AppState, types::{ - api, + api, domain, storage::{self, enums as storage_enums}, }, }; @@ -23,12 +24,20 @@ newtype!( #[async_trait::async_trait] pub(crate) trait MandateResponseExt: Sized { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self>; + async fn from_db_mandate( + state: &AppState, + key_store: domain::MerchantKeyStore, + mandate: storage::Mandate, + ) -> RouterResult<Self>; } #[async_trait::async_trait] impl MandateResponseExt for MandateResponse { - async fn from_db_mandate(state: &AppState, mandate: storage::Mandate) -> RouterResult<Self> { + async fn from_db_mandate( + state: &AppState, + key_store: domain::MerchantKeyStore, + mandate: storage::Mandate, + ) -> RouterResult<Self> { let db = &*state.store; let payment_method = db .find_payment_method(&mandate.payment_method_id) @@ -36,21 +45,35 @@ impl MandateResponseExt for MandateResponse { .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; let card = if payment_method.payment_method == storage_enums::PaymentMethod::Card { - let card = payment_methods::cards::get_card_from_locker( - state, - &payment_method.customer_id, - &payment_method.merchant_id, - &payment_method.payment_method_id, - ) - .await?; - let card_detail = payment_methods::transformers::get_card_detail(&payment_method, card) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while getting card details")?; - Some(MandateCardDetails::from(card_detail).into_inner()) + // if locker is disabled , decrypt the payment method data + let card_details = if state.conf.locker.locker_enabled { + let card = payment_methods::cards::get_card_from_locker( + state, + &payment_method.customer_id, + &payment_method.merchant_id, + &payment_method.payment_method_id, + ) + .await?; + + payment_methods::transformers::get_card_detail(&payment_method, card) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while getting card details")? + } else { + payment_methods::cards::get_card_details_without_locker_fallback( + &payment_method, + key_store.key.get_inner().peek(), + state, + ) + .await? + }; + + Some(MandateCardDetails::from(card_details).into_inner()) } else { None }; - + let payment_method_type = payment_method + .payment_method_type + .map(|pmt| pmt.to_string()); Ok(Self { mandate_id: mandate.mandate_id, customer_acceptance: Some(api::payments::CustomerAcceptance { @@ -68,6 +91,7 @@ impl MandateResponseExt for MandateResponse { card, status: mandate.mandate_status, payment_method: payment_method.payment_method.to_string(), + payment_method_type, payment_method_id: mandate.payment_method_id, }) } @@ -84,6 +108,10 @@ impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails { scheme: card_details_from_locker.scheme, issuer_country: card_details_from_locker.issuer_country, card_fingerprint: card_details_from_locker.card_fingerprint, + card_isin: card_details_from_locker.card_isin, + card_issuer: card_details_from_locker.card_issuer, + card_network: card_details_from_locker.card_network, + card_type: card_details_from_locker.card_type, } .into() } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 358a591a667..268ebd1d3ac 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -33,6 +33,7 @@ host = "" host_rs = "" mock_locker = true basilisk_host = "" +locker_enabled = true [forex_api] call_delay = 21600 diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index b2f5d3ea52c..02df6324a06 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4421,11 +4421,37 @@ "description": "Card Holder's Nick Name", "example": "John Doe", "nullable": true + }, + "card_issuing_country": { + "type": "string", + "description": "Card Issuing Country", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_issuer": { + "type": "string", + "description": "Issuer Bank for Card", + "nullable": true + }, + "card_type": { + "type": "string", + "description": "Card Type", + "nullable": true } } }, "CardDetailFromLocker": { "type": "object", + "required": [ + "saved_to_locker" + ], "properties": { "scheme": { "type": "string", @@ -4462,6 +4488,29 @@ "nick_name": { "type": "string", "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_isin": { + "type": "string", + "nullable": true + }, + "card_issuer": { + "type": "string", + "nullable": true + }, + "card_type": { + "type": "string", + "nullable": true + }, + "saved_to_locker": { + "type": "boolean" } } }, @@ -6884,6 +6933,29 @@ "type": "string", "description": "A unique identifier alias to identify a particular card", "nullable": true + }, + "card_isin": { + "type": "string", + "description": "The first 6 digits of card", + "nullable": true + }, + "card_issuer": { + "type": "string", + "description": "The bank that issued the card", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_type": { + "type": "string", + "description": "The type of the payment card", + "nullable": true } } }, @@ -6932,6 +7004,11 @@ "type": "string", "description": "The payment method" }, + "payment_method_type": { + "type": "string", + "description": "The payment method type", + "nullable": true + }, "card": { "allOf": [ {
2024-01-15T11:31:45Z
## Description Add locker config to enable or disable locker , so that if the locker is enabled we can store the card_details in the locker else if the config is disabled we don't Also this PR involvesaddition in the `MandateResponse`. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This Feature provides an option for the merchant whether or not to save the card at hyperswitch . Saving the card at hyperswitch is not necessary if the mandate is created at the processor level. #
2f693ad1fd857280ef30c6cc0297fb926f0e79e8
- Create an MA & MCA - Disable the `locker_enabled` config > Create a Mandate payment , the details will not be stored in Locker and payment will be successful > List PaymentMethods for a Customer won't have any details as the card was never stored > List the Mandates would have mandate details ![Screenshot 2024-01-16 at 4 38 43 PM](https://github.com/juspay/hyperswitch/assets/55580080/c9d5d11b-b31f-4a58-a324-f92c376a7c26) ![Screenshot 2024-01-16 at 4 38 59 PM](https://github.com/juspay/hyperswitch/assets/55580080/32645dfa-c962-43a2-9e7f-ca1056415560) ![Screenshot 2024-01-16 at 4 39 10 PM](https://github.com/juspay/hyperswitch/assets/55580080/f413bd94-b74c-4a1b-bf22-fbc335a05e56) ![Screenshot 2024-01-16 at 4 39 26 PM](https://github.com/juspay/hyperswitch/assets/55580080/2745fabd-bc81-4d2b-ab53-d6829fa53d13) ![Screenshot 2024-01-16 at 4 39 38 PM](https://github.com/juspay/hyperswitch/assets/55580080/25221f1c-7932-4295-9a6e-083355513c15) - Enable the `locker_enabled` config > Create a Mandate payment , the details will be stored in Locker and payment will be successful > List PaymentMethods for a Customer would have details of the card that was stored > List the Mandates ![Screenshot 2024-01-16 at 4 33 56 PM](https://github.com/juspay/hyperswitch/assets/55580080/174a1933-9112-4088-893c-12c4e84b3148) ![Screenshot 2024-01-16 at 4 34 57 PM](https://github.com/juspay/hyperswitch/assets/55580080/2a5f46e7-86b0-470e-89a6-3a8f0a225c3b) ![Screenshot 2024-01-16 at 4 35 18 PM](https://github.com/juspay/hyperswitch/assets/55580080/66a1df1f-0f8a-418e-a122-570508eb97a9) ![Screenshot 2024-01-16 at 4 35 33 PM](https://github.com/juspay/hyperswitch/assets/55580080/8c5fe598-9cad-498f-88eb-ef9ca0c3018b) ![Screenshot 2024-01-16 at 4 35 51 PM](https://github.com/juspay/hyperswitch/assets/55580080/8d05dbcb-ef2d-4c2a-b326-56393ed5b16e) ![Screenshot 2024-01-16 at 4 36 32 PM](https://github.com/juspay/hyperswitch/assets/55580080/0e3e9272-27b5-44de-9c3a-4e1e942faee9) -When we do a list mandates we have an additional field `payment_method_type` ![Screenshot 2024-01-18 at 4 27 53 PM](https://github.com/juspay/hyperswitch/assets/55580080/7b2455e7-889b-4e01-979d-56353ce60f49)
[ "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/mandates.rs", "crates/api_models/src/payment_methods.rs", "crates/router/src/configs/defaults.rs", "crates/router/src/configs/settings.rs", "crates/router/src/core/locker_migration.rs", "cra...
juspay/hyperswitch
juspay__hyperswitch-3347
Bug: Refactor `s3` to extend other storage logics and provide a runtime flag for the same Provide a runtime flag to handle file storage operations
diff --git a/Cargo.lock b/Cargo.lock index f920b1ea9c5..b86facad816 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2481,6 +2481,7 @@ dependencies = [ "async-trait", "aws-config", "aws-sdk-kms", + "aws-sdk-s3", "aws-sdk-sesv2", "aws-sdk-sts", "aws-smithy-client", @@ -2726,9 +2727,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", "futures-sink", @@ -2736,9 +2737,9 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" @@ -2764,9 +2765,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-lite" @@ -2785,9 +2786,9 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", @@ -2796,15 +2797,15 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" [[package]] name = "futures-task" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-timer" @@ -2814,9 +2815,9 @@ checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" [[package]] name = "futures-util" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-channel", "futures-core", @@ -5155,8 +5156,6 @@ dependencies = [ "async-bb8-diesel", "async-trait", "awc", - "aws-config", - "aws-sdk-s3", "base64 0.21.5", "bb8", "bigdecimal", diff --git a/config/config.example.toml b/config/config.example.toml index 0ad50736e9e..27d1f8b18c5 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -535,3 +535,11 @@ refund_analytics_topic = "topic" # Kafka topic to be used for Refund events api_logs_topic = "topic" # Kafka topic to be used for incoming api events connector_logs_topic = "topic" # Kafka topic to be used for connector api events outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events + +# File storage configuration +[file_storage] +file_storage_backend = "aws_s3" # File storage backend to be used + +[file_storage.aws_s3] +region = "us-east-1" # The AWS region used by the AWS S3 for file storage +bucket_name = "bucket1" # The AWS S3 bucket name for file storage diff --git a/config/development.toml b/config/development.toml index b23f68680e6..5fbe9607cd3 100644 --- a/config/development.toml +++ b/config/development.toml @@ -544,3 +544,6 @@ client_id = "" client_secret = "" partner_id = "" enabled = true + +[file_storage] +file_storage_backend = "file_system" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8af1528e177..8dd01a3d1ce 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -399,3 +399,6 @@ enabled = true [events] source = "logs" + +[file_storage] +file_storage_backend = "file_system" diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 6552b57b0e5..bf836af71a7 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true [features] kms = ["dep:aws-config", "dep:aws-sdk-kms"] email = ["dep:aws-config"] +aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = [ "dep:vaultrs" ] [dependencies] @@ -18,6 +19,7 @@ aws-config = { version = "0.55.3", optional = true } aws-sdk-kms = { version = "0.28.0", optional = true } aws-sdk-sesv2 = "0.28.0" aws-sdk-sts = "0.28.0" +aws-sdk-s3 = { version = "0.28.0", optional = true } aws-smithy-client = "0.55.3" base64 = "0.21.2" dyn-clone = "1.0.11" diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs new file mode 100644 index 00000000000..fb419b6ec64 --- /dev/null +++ b/crates/external_services/src/file_storage.rs @@ -0,0 +1,96 @@ +//! +//! Module for managing file storage operations with support for multiple storage schemes. +//! + +use std::fmt::{Display, Formatter}; + +use common_utils::errors::CustomResult; + +/// Includes functionality for AWS S3 storage operations. +#[cfg(feature = "aws_s3")] +mod aws_s3; + +mod file_system; + +/// Enum representing different file storage configurations, allowing for multiple storage schemes. +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(tag = "file_storage_backend")] +#[serde(rename_all = "snake_case")] +pub enum FileStorageConfig { + /// AWS S3 storage configuration. + #[cfg(feature = "aws_s3")] + AwsS3 { + /// Configuration for AWS S3 file storage. + aws_s3: aws_s3::AwsFileStorageConfig, + }, + /// Local file system storage configuration. + #[default] + FileSystem, +} + +impl FileStorageConfig { + /// Validates the file storage configuration. + pub fn validate(&self) -> Result<(), InvalidFileStorageConfig> { + match self { + #[cfg(feature = "aws_s3")] + Self::AwsS3 { aws_s3 } => aws_s3.validate(), + Self::FileSystem => Ok(()), + } + } + + /// Retrieves the appropriate file storage client based on the file storage configuration. + pub async fn get_file_storage_client(&self) -> Box<dyn FileStorageInterface> { + match self { + #[cfg(feature = "aws_s3")] + Self::AwsS3 { aws_s3 } => Box::new(aws_s3::AwsFileStorageClient::new(aws_s3).await), + Self::FileSystem => Box::new(file_system::FileSystem), + } + } +} + +/// Trait for file storage operations +#[async_trait::async_trait] +pub trait FileStorageInterface: dyn_clone::DynClone + Sync + Send { + /// Uploads a file to the selected storage scheme. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError>; + + /// Deletes a file from the selected storage scheme. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError>; + + /// Retrieves a file from the selected storage scheme. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError>; +} + +dyn_clone::clone_trait_object!(FileStorageInterface); + +/// Error thrown when the file storage config is invalid +#[derive(Debug, Clone)] +pub struct InvalidFileStorageConfig(&'static str); + +impl std::error::Error for InvalidFileStorageConfig {} + +impl Display for InvalidFileStorageConfig { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "file_storage: {}", self.0) + } +} + +/// Represents errors that can occur during file storage operations. +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum FileStorageError { + /// Indicates that the file upload operation failed. + #[error("Failed to upload file")] + UploadFailed, + + /// Indicates that the file retrieval operation failed. + #[error("Failed to retrieve file")] + RetrieveFailed, + + /// Indicates that the file deletion operation failed. + #[error("Failed to delete file")] + DeleteFailed, +} diff --git a/crates/external_services/src/file_storage/aws_s3.rs b/crates/external_services/src/file_storage/aws_s3.rs new file mode 100644 index 00000000000..86d1c0f0efa --- /dev/null +++ b/crates/external_services/src/file_storage/aws_s3.rs @@ -0,0 +1,158 @@ +use aws_config::meta::region::RegionProviderChain; +use aws_sdk_s3::{ + operation::{ + delete_object::DeleteObjectError, get_object::GetObjectError, put_object::PutObjectError, + }, + Client, +}; +use aws_sdk_sts::config::Region; +use common_utils::{errors::CustomResult, ext_traits::ConfigExt}; +use error_stack::ResultExt; + +use super::InvalidFileStorageConfig; +use crate::file_storage::{FileStorageError, FileStorageInterface}; + +/// Configuration for AWS S3 file storage. +#[derive(Debug, serde::Deserialize, Clone, Default)] +#[serde(default)] +pub struct AwsFileStorageConfig { + /// The AWS region to send file uploads + region: String, + /// The AWS s3 bucket to send file uploads + bucket_name: String, +} + +impl AwsFileStorageConfig { + /// Validates the AWS S3 file storage configuration. + pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> { + use common_utils::fp_utils::when; + + when(self.region.is_default_or_empty(), || { + Err(InvalidFileStorageConfig("aws s3 region must not be empty")) + })?; + + when(self.bucket_name.is_default_or_empty(), || { + Err(InvalidFileStorageConfig( + "aws s3 bucket name must not be empty", + )) + }) + } +} + +/// AWS S3 file storage client. +#[derive(Debug, Clone)] +pub(super) struct AwsFileStorageClient { + /// AWS S3 client + inner_client: Client, + /// The name of the AWS S3 bucket. + bucket_name: String, +} + +impl AwsFileStorageClient { + /// Creates a new AWS S3 file storage client. + pub(super) async fn new(config: &AwsFileStorageConfig) -> Self { + let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone())); + let sdk_config = aws_config::from_env().region(region_provider).load().await; + Self { + inner_client: Client::new(&sdk_config), + bucket_name: config.bucket_name.clone(), + } + } + + /// Uploads a file to AWS S3. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), AwsS3StorageError> { + self.inner_client + .put_object() + .bucket(&self.bucket_name) + .key(file_key) + .body(file.into()) + .send() + .await + .map_err(AwsS3StorageError::UploadFailure)?; + Ok(()) + } + + /// Deletes a file from AWS S3. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), AwsS3StorageError> { + self.inner_client + .delete_object() + .bucket(&self.bucket_name) + .key(file_key) + .send() + .await + .map_err(AwsS3StorageError::DeleteFailure)?; + Ok(()) + } + + /// Retrieves a file from AWS S3. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, AwsS3StorageError> { + Ok(self + .inner_client + .get_object() + .bucket(&self.bucket_name) + .key(file_key) + .send() + .await + .map_err(AwsS3StorageError::RetrieveFailure)? + .body + .collect() + .await + .map_err(AwsS3StorageError::UnknownError)? + .to_vec()) + } +} + +#[async_trait::async_trait] +impl FileStorageInterface for AwsFileStorageClient { + /// Uploads a file to AWS S3. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError> { + self.upload_file(file_key, file) + .await + .change_context(FileStorageError::UploadFailed)?; + Ok(()) + } + + /// Deletes a file from AWS S3. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> { + self.delete_file(file_key) + .await + .change_context(FileStorageError::DeleteFailed)?; + Ok(()) + } + + /// Retrieves a file from AWS S3. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> { + Ok(self + .retrieve_file(file_key) + .await + .change_context(FileStorageError::RetrieveFailed)?) + } +} + +/// Enum representing errors that can occur during AWS S3 file storage operations. +#[derive(Debug, thiserror::Error)] +enum AwsS3StorageError { + /// Error indicating that file upload to S3 failed. + #[error("File upload to S3 failed: {0:?}")] + UploadFailure(aws_smithy_client::SdkError<PutObjectError>), + + /// Error indicating that file retrieval from S3 failed. + #[error("File retrieve from S3 failed: {0:?}")] + RetrieveFailure(aws_smithy_client::SdkError<GetObjectError>), + + /// Error indicating that file deletion from S3 failed. + #[error("File delete from S3 failed: {0:?}")] + DeleteFailure(aws_smithy_client::SdkError<DeleteObjectError>), + + /// Unknown error occurred. + #[error("Unknown error occurred: {0:?}")] + UnknownError(aws_sdk_s3::primitives::ByteStreamError), +} diff --git a/crates/external_services/src/file_storage/file_system.rs b/crates/external_services/src/file_storage/file_system.rs new file mode 100644 index 00000000000..15ca84deeb8 --- /dev/null +++ b/crates/external_services/src/file_storage/file_system.rs @@ -0,0 +1,144 @@ +//! +//! Module for local file system storage operations +//! + +use std::{ + fs::{remove_file, File}, + io::{Read, Write}, + path::PathBuf, +}; + +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; + +use crate::file_storage::{FileStorageError, FileStorageInterface}; + +/// Constructs the file path for a given file key within the file system. +/// The file path is generated based on the workspace path and the provided file key. +fn get_file_path(file_key: impl AsRef<str>) -> PathBuf { + let mut file_path = PathBuf::new(); + #[cfg(feature = "logs")] + file_path.push(router_env::env::workspace_path()); + #[cfg(not(feature = "logs"))] + file_path.push(std::env::current_dir().unwrap_or(".".into())); + + file_path.push("files"); + file_path.push(file_key.as_ref()); + file_path +} + +/// Represents a file system for storing and managing files locally. +#[derive(Debug, Clone)] +pub(super) struct FileSystem; + +impl FileSystem { + /// Saves the provided file data to the file system under the specified file key. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileSystemStorageError> { + let file_path = get_file_path(file_key); + + // Ignore the file name and create directories in the `file_path` if not exists + std::fs::create_dir_all( + file_path + .parent() + .ok_or(FileSystemStorageError::CreateDirFailed) + .into_report() + .attach_printable("Failed to obtain parent directory")?, + ) + .into_report() + .change_context(FileSystemStorageError::CreateDirFailed)?; + + let mut file_handler = File::create(file_path) + .into_report() + .change_context(FileSystemStorageError::CreateFailure)?; + file_handler + .write_all(&file) + .into_report() + .change_context(FileSystemStorageError::WriteFailure)?; + Ok(()) + } + + /// Deletes the file associated with the specified file key from the file system. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileSystemStorageError> { + let file_path = get_file_path(file_key); + remove_file(file_path) + .into_report() + .change_context(FileSystemStorageError::DeleteFailure)?; + Ok(()) + } + + /// Retrieves the file content associated with the specified file key from the file system. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileSystemStorageError> { + let mut received_data: Vec<u8> = Vec::new(); + let file_path = get_file_path(file_key); + let mut file = File::open(file_path) + .into_report() + .change_context(FileSystemStorageError::FileOpenFailure)?; + file.read_to_end(&mut received_data) + .into_report() + .change_context(FileSystemStorageError::ReadFailure)?; + Ok(received_data) + } +} + +#[async_trait::async_trait] +impl FileStorageInterface for FileSystem { + /// Saves the provided file data to the file system under the specified file key. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError> { + self.upload_file(file_key, file) + .await + .change_context(FileStorageError::UploadFailed)?; + Ok(()) + } + + /// Deletes the file associated with the specified file key from the file system. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> { + self.delete_file(file_key) + .await + .change_context(FileStorageError::DeleteFailed)?; + Ok(()) + } + + /// Retrieves the file content associated with the specified file key from the file system. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> { + Ok(self + .retrieve_file(file_key) + .await + .change_context(FileStorageError::RetrieveFailed)?) + } +} + +/// Represents an error that can occur during local file system storage operations. +#[derive(Debug, thiserror::Error)] +enum FileSystemStorageError { + /// Error indicating opening a file failed + #[error("Failed while opening the file")] + FileOpenFailure, + + /// Error indicating file creation failed. + #[error("Failed to create file")] + CreateFailure, + + /// Error indicating reading a file failed. + #[error("Failed while reading the file")] + ReadFailure, + + /// Error indicating writing to a file failed. + #[error("Failed while writing into file")] + WriteFailure, + + /// Error indicating file deletion failed. + #[error("Failed while deleting the file")] + DeleteFailure, + + /// Error indicating directory creation failed + #[error("Failed while creating a directory")] + CreateDirFailed, +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 9bf4916eec3..bba65873e91 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -9,6 +9,7 @@ pub mod email; #[cfg(feature = "kms")] pub mod kms; +pub mod file_storage; #[cfg(feature = "hashicorp-vault")] pub mod hashicorp_vault; diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e575daf7e7a..3d129edfe3f 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,10 +10,10 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] -aws_s3 = ["dep:aws-sdk-s3", "dep:aws-config"] -kms = ["external_services/kms", "dep:aws-config"] +aws_s3 = ["external_services/aws_s3"] +kms = ["external_services/kms"] hashicorp-vault = ["external_services/hashicorp-vault"] -email = ["external_services/email", "dep:aws-config", "olap"] +email = ["external_services/email", "olap"] frm = [] stripe = ["dep:serde_qs"] release = ["kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] @@ -42,8 +42,6 @@ actix-web = "4.3.1" async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } argon2 = { version = "0.5.0", features = ["std"] } async-trait = "0.1.68" -aws-config = { version = "0.55.3", optional = true } -aws-sdk-s3 = { version = "0.28.0", optional = true } base64 = "0.21.2" bb8 = "0.8" bigdecimal = "0.3.1" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3c1d9f7d397..146a1ace28e 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -11,6 +11,7 @@ use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; #[cfg(feature = "email")] use external_services::email::EmailSettings; +use external_services::file_storage::FileStorageConfig; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; #[cfg(feature = "kms")] @@ -90,10 +91,9 @@ pub struct Settings { pub api_keys: ApiKeys, #[cfg(feature = "kms")] pub kms: kms::KmsConfig, + pub file_storage: FileStorageConfig, #[cfg(feature = "hashicorp-vault")] pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, - #[cfg(feature = "aws_s3")] - pub file_upload_config: FileUploadConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] @@ -721,16 +721,6 @@ pub struct ApiKeys { pub expiry_reminder_days: Vec<u8>, } -#[cfg(feature = "aws_s3")] -#[derive(Debug, Deserialize, Clone, Default)] -#[serde(default)] -pub struct FileUploadConfig { - /// The AWS region to send file uploads - pub region: String, - /// The AWS s3 bucket to send file uploads - pub bucket_name: String, -} - #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { #[serde(deserialize_with = "deser_to_get_connectors")] @@ -853,8 +843,11 @@ impl Settings { self.kms .validate() .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?; - #[cfg(feature = "aws_s3")] - self.file_upload_config.validate()?; + + self.file_storage + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; + self.lock_settings.validate()?; self.events.validate()?; Ok(()) diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 0b286ece843..910ae754347 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -127,25 +127,6 @@ impl super::settings::DrainerSettings { } } -#[cfg(feature = "aws_s3")] -impl super::settings::FileUploadConfig { - pub fn validate(&self) -> Result<(), ApplicationError> { - use common_utils::fp_utils::when; - - when(self.region.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "s3 region must not be empty".into(), - )) - })?; - - when(self.bucket_name.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "s3 bucket name must not be empty".into(), - )) - }) - } -} - impl super::settings::ApiKeys { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs index f3e56489806..d3f490a0a6c 100644 --- a/crates/router/src/core/files.rs +++ b/crates/router/src/core/files.rs @@ -1,9 +1,4 @@ pub mod helpers; -#[cfg(feature = "aws_s3")] -pub mod s3_utils; - -#[cfg(not(feature = "aws_s3"))] -pub mod fs_utils; use api_models::files; use error_stack::{IntoReport, ResultExt}; @@ -29,10 +24,7 @@ pub async fn files_create_core( ) .await?; let file_id = common_utils::generate_id(consts::ID_LENGTH, "file"); - #[cfg(feature = "aws_s3")] let file_key = format!("{}/{}", merchant_account.merchant_id, file_id); - #[cfg(not(feature = "aws_s3"))] - let file_key = format!("{}_{}", merchant_account.merchant_id, file_id); let file_new = diesel_models::file::FileMetadataNew { file_id: file_id.clone(), merchant_id: merchant_account.merchant_id.clone(), diff --git a/crates/router/src/core/files/fs_utils.rs b/crates/router/src/core/files/fs_utils.rs deleted file mode 100644 index 795f2fad759..00000000000 --- a/crates/router/src/core/files/fs_utils.rs +++ /dev/null @@ -1,57 +0,0 @@ -use std::{ - fs::{remove_file, File}, - io::{Read, Write}, - path::PathBuf, -}; - -use common_utils::errors::CustomResult; -use error_stack::{IntoReport, ResultExt}; - -use crate::{core::errors, env}; - -pub fn get_file_path(file_key: String) -> PathBuf { - let mut file_path = PathBuf::new(); - file_path.push(env::workspace_path()); - file_path.push("files"); - file_path.push(file_key); - file_path -} - -pub fn save_file_to_fs( - file_key: String, - file_data: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - let file_path = get_file_path(file_key); - let mut file = File::create(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to create file")?; - file.write_all(&file_data) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while writing into file")?; - Ok(()) -} - -pub fn delete_file_from_fs(file_key: String) -> CustomResult<(), errors::ApiErrorResponse> { - let file_path = get_file_path(file_key); - remove_file(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while deleting the file")?; - Ok(()) -} - -pub fn retrieve_file_from_fs(file_key: String) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - let mut received_data: Vec<u8> = Vec::new(); - let file_path = get_file_path(file_key); - let mut file = File::open(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while opening the file")?; - file.read_to_end(&mut received_data) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while reading the file")?; - Ok(received_data) -} diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 9205d42aeee..0a509b238af 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -6,7 +6,7 @@ use futures::TryStreamExt; use crate::{ core::{ errors::{self, StorageErrorExt}, - files, payments, utils, + payments, utils, }, routes::AppState, services, @@ -30,37 +30,6 @@ pub async fn get_file_purpose(field: &mut Field) -> Option<api::FilePurpose> { } } -pub async fn upload_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, - file: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::upload_file_to_s3(state, file_key, file).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::save_file_to_fs(file_key, file); -} - -pub async fn delete_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, -) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::delete_file_from_s3(state, file_key).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::delete_file_from_fs(file_key); -} - -pub async fn retrieve_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, -) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::retrieve_file_from_s3(state, file_key).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::retrieve_file_from_fs(file_key); -} - pub async fn validate_file_upload( state: &AppState, merchant_account: domain::MerchantAccount, @@ -132,14 +101,11 @@ pub async fn delete_file_using_file_id( .attach_printable("File not available")?, }; match provider { - diesel_models::enums::FileUploadProvider::Router => { - delete_file( - #[cfg(feature = "aws_s3")] - state, - provider_file_id, - ) + diesel_models::enums::FileUploadProvider::Router => state + .file_storage_client + .delete_file(&provider_file_id) .await - } + .change_context(errors::ApiErrorResponse::InternalServerError), _ => Err(errors::ApiErrorResponse::FileProviderNotSupported { message: "Not Supported because provider is not Router".to_string(), } @@ -234,12 +200,11 @@ pub async fn retrieve_file_and_provider_file_id_from_file_id( match provider { diesel_models::enums::FileUploadProvider::Router => Ok(( Some( - retrieve_file( - #[cfg(feature = "aws_s3")] - state, - provider_file_id.clone(), - ) - .await?, + state + .file_storage_client + .retrieve_file(&provider_file_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?, ), Some(provider_file_id), )), @@ -364,13 +329,11 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id( payment_attempt.merchant_connector_id, )) } else { - upload_file( - #[cfg(feature = "aws_s3")] - state, - file_key.clone(), - create_file_request.file.clone(), - ) - .await?; + state + .file_storage_client + .upload_file(&file_key, create_file_request.file.clone()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(( file_key, api_models::enums::FileUploadProvider::Router, diff --git a/crates/router/src/core/files/s3_utils.rs b/crates/router/src/core/files/s3_utils.rs deleted file mode 100644 index 228c23528cd..00000000000 --- a/crates/router/src/core/files/s3_utils.rs +++ /dev/null @@ -1,87 +0,0 @@ -use aws_config::{self, meta::region::RegionProviderChain}; -use aws_sdk_s3::{config::Region, Client}; -use common_utils::errors::CustomResult; -use error_stack::{IntoReport, ResultExt}; -use futures::TryStreamExt; - -use crate::{core::errors, routes}; - -async fn get_aws_client(state: &routes::AppState) -> Client { - let region_provider = - RegionProviderChain::first_try(Region::new(state.conf.file_upload_config.region.clone())); - let sdk_config = aws_config::from_env().region(region_provider).load().await; - Client::new(&sdk_config) -} - -pub async fn upload_file_to_s3( - state: &routes::AppState, - file_key: String, - file: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Upload file to S3 - let upload_res = client - .put_object() - .bucket(bucket_name) - .key(file_key.clone()) - .body(file.into()) - .send() - .await; - upload_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File upload to S3 failed")?; - Ok(()) -} - -pub async fn delete_file_from_s3( - state: &routes::AppState, - file_key: String, -) -> CustomResult<(), errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Delete file from S3 - let delete_res = client - .delete_object() - .bucket(bucket_name) - .key(file_key) - .send() - .await; - delete_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File delete from S3 failed")?; - Ok(()) -} - -pub async fn retrieve_file_from_s3( - state: &routes::AppState, - file_key: String, -) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Get file data from S3 - let get_res = client - .get_object() - .bucket(bucket_name) - .key(file_key) - .send() - .await; - let mut object = get_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File retrieve from S3 failed")?; - let mut received_data: Vec<u8> = Vec::new(); - while let Some(bytes) = object - .body - .try_next() - .await - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid file data received from S3")? - { - received_data.extend_from_slice(&bytes); // Collect the bytes in the Vec - } - Ok(received_data) -} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f490cee8dab..2b26a5e7586 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -5,6 +5,7 @@ use actix_web::{web, Scope}; use analytics::AnalyticsConfig; #[cfg(feature = "email")] use external_services::email::{ses::AwsSes, EmailService}; +use external_services::file_storage::FileStorageInterface; #[cfg(all(feature = "olap", feature = "hashicorp-vault"))] use external_services::hashicorp_vault::decrypt::VaultFetch; #[cfg(feature = "kms")] @@ -68,6 +69,7 @@ pub struct AppState { #[cfg(feature = "olap")] pub pool: crate::analytics::AnalyticsProvider, pub request_id: Option<RequestId>, + pub file_storage_client: Box<dyn FileStorageInterface>, } impl scheduler::SchedulerAppState for AppState { @@ -266,6 +268,8 @@ impl AppState { #[cfg(feature = "email")] let email_client = Arc::new(create_email_client(&conf).await); + let file_storage_client = conf.file_storage.get_file_storage_client().await; + Self { flow_name: String::from("default"), store, @@ -279,6 +283,7 @@ impl AppState { #[cfg(feature = "olap")] pool, request_id: None, + file_storage_client, } }) .await diff --git a/docker-compose.yml b/docker-compose.yml index 3839269a522..e55008f1e34 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -54,6 +54,7 @@ services: - router_net volumes: - ./config:/local/config + - ./files:/local/bin/files labels: logs: "promtail" healthcheck:
2024-01-14T14:27:35Z
## Description <!-- Describe your changes in detail --> This PR includes refactoring for: * Enabling easy extension of other file storage schemes. * Providing a runtime flag for the file storage feature. * Restrict the file storage objects(structs, methods) visibility wherever possible. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #3338, Closes #3347 # ### File System 1. File uploading ``` curl --location --request POST 'localhost:8080/files' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' \ --header 'Content-Type: multipart/form-data; boundary=6467930559a8e09e-babf866111649afb-06f42165ce9a45a7-bc825186544537e1' \ --header 'Accept-Encoding: gzip' \ --form 'purpose="dispute_evidence"' \ --form 'file=@"/Users/sai.harsha/Desktop/dummy.pdf"' \ --form 'dispute_id="dp_Hv9m2MJGRjptYmEYPqFa"' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/ddec5aff-a0e3-4d09-9d0d-32f698e0c3cc) 2. File retrieve ``` curl --location --request GET 'localhost:8080/files/file_qXP0X6uAgLwSvswj8T41' \ --header 'Accept: application/json' \ --header 'api-key: dev_H3Uf7cssLge9XnWZZfV2M5xwqroMHt46cXh0EwXJQHTdYuBTVC3KVnA5Fo45hagw' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/efe193e3-b5d7-4f30-8546-c499a6c36483) 3. File delete ``` curl --location --request DELETE 'localhost:8080/files/file_z4giuhfczJqbXwNhazqS' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/a724d0b7-1c80-4c62-9b2e-2fd20205c681) ### Aws S3 1. File uploading ![image](https://github.com/juspay/hyperswitch/assets/70657455/e4077964-e117-4f50-8e9b-25bdcb794a9a) 2. File retrieve ![image](https://github.com/juspay/hyperswitch/assets/70657455/b7d3e799-0fde-48a2-aac0-513faa49523e) 3. File delete ![image (1)](https://github.com/juspay/hyperswitch/assets/70657455/e398faeb-0697-483c-8a41-dd5bd47d5e18)
3fbffdc242dafe7983c542573b7c6362f99331e6
* Create a dispute and get the `dispute_id` ### File System 1. File uploading ``` curl --location --request POST 'localhost:8080/files' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' \ --header 'Content-Type: multipart/form-data; boundary=6467930559a8e09e-babf866111649afb-06f42165ce9a45a7-bc825186544537e1' \ --header 'Accept-Encoding: gzip' \ --form 'purpose="dispute_evidence"' \ --form 'file=@"/Users/sai.harsha/Desktop/dummy.pdf"' \ --form 'dispute_id="dp_Hv9m2MJGRjptYmEYPqFa"' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/ddec5aff-a0e3-4d09-9d0d-32f698e0c3cc) 2. File retrieve ``` curl --location --request GET 'localhost:8080/files/file_qXP0X6uAgLwSvswj8T41' \ --header 'Accept: application/json' \ --header 'api-key: dev_H3Uf7cssLge9XnWZZfV2M5xwqroMHt46cXh0EwXJQHTdYuBTVC3KVnA5Fo45hagw' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/efe193e3-b5d7-4f30-8546-c499a6c36483) 3. File delete ``` curl --location --request DELETE 'localhost:8080/files/file_z4giuhfczJqbXwNhazqS' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/a724d0b7-1c80-4c62-9b2e-2fd20205c681) ### Aws S3 1. File uploading ![image](https://github.com/juspay/hyperswitch/assets/70657455/e4077964-e117-4f50-8e9b-25bdcb794a9a) 2. File retrieve ![image](https://github.com/juspay/hyperswitch/assets/70657455/b7d3e799-0fde-48a2-aac0-513faa49523e) 3. File delete ![image (1)](https://github.com/juspay/hyperswitch/assets/70657455/e398faeb-0697-483c-8a41-dd5bd47d5e18)
[ "Cargo.lock", "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/external_services/Cargo.toml", "crates/external_services/src/file_storage.rs", "crates/external_services/src/file_storage/aws_s3.rs", "crates/external_services/src/file_storage/file_system.rs",...
juspay/hyperswitch
juspay__hyperswitch-3338
Bug: [REFACTOR] Enable runtime flag for `s3` feature ### Feature Description Tracking issue for refactoring `s3` to include compile time + runtime time flag Current implementation - We are building 2 docker images, one image contains all the release features including `kms`, `s3`, etc and other without these features which are getting pushed to the public docker hub. This was to ensure that anyone who wants to try out Hyperswitch locally by pulling the pre-built docker image, it shouldn't be a hassle for he/she to setup `s3`. For this very reason we were pushing 2 docker images which was a temporary solution ### Possible Implementation Providing support for enabling or disabling s3 feature in runtime so that we no longer have to build 2 images. ### Tasks - [x] #3340 - [x] #3347 ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index f920b1ea9c5..b86facad816 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2481,6 +2481,7 @@ dependencies = [ "async-trait", "aws-config", "aws-sdk-kms", + "aws-sdk-s3", "aws-sdk-sesv2", "aws-sdk-sts", "aws-smithy-client", @@ -2726,9 +2727,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", "futures-sink", @@ -2736,9 +2737,9 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" @@ -2764,9 +2765,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-lite" @@ -2785,9 +2786,9 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", @@ -2796,15 +2797,15 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" [[package]] name = "futures-task" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-timer" @@ -2814,9 +2815,9 @@ checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" [[package]] name = "futures-util" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-channel", "futures-core", @@ -5155,8 +5156,6 @@ dependencies = [ "async-bb8-diesel", "async-trait", "awc", - "aws-config", - "aws-sdk-s3", "base64 0.21.5", "bb8", "bigdecimal", diff --git a/config/config.example.toml b/config/config.example.toml index 0ad50736e9e..27d1f8b18c5 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -535,3 +535,11 @@ refund_analytics_topic = "topic" # Kafka topic to be used for Refund events api_logs_topic = "topic" # Kafka topic to be used for incoming api events connector_logs_topic = "topic" # Kafka topic to be used for connector api events outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webhook events + +# File storage configuration +[file_storage] +file_storage_backend = "aws_s3" # File storage backend to be used + +[file_storage.aws_s3] +region = "us-east-1" # The AWS region used by the AWS S3 for file storage +bucket_name = "bucket1" # The AWS S3 bucket name for file storage diff --git a/config/development.toml b/config/development.toml index b23f68680e6..5fbe9607cd3 100644 --- a/config/development.toml +++ b/config/development.toml @@ -544,3 +544,6 @@ client_id = "" client_secret = "" partner_id = "" enabled = true + +[file_storage] +file_storage_backend = "file_system" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8af1528e177..8dd01a3d1ce 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -399,3 +399,6 @@ enabled = true [events] source = "logs" + +[file_storage] +file_storage_backend = "file_system" diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index 6552b57b0e5..bf836af71a7 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -10,6 +10,7 @@ license.workspace = true [features] kms = ["dep:aws-config", "dep:aws-sdk-kms"] email = ["dep:aws-config"] +aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = [ "dep:vaultrs" ] [dependencies] @@ -18,6 +19,7 @@ aws-config = { version = "0.55.3", optional = true } aws-sdk-kms = { version = "0.28.0", optional = true } aws-sdk-sesv2 = "0.28.0" aws-sdk-sts = "0.28.0" +aws-sdk-s3 = { version = "0.28.0", optional = true } aws-smithy-client = "0.55.3" base64 = "0.21.2" dyn-clone = "1.0.11" diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs new file mode 100644 index 00000000000..fb419b6ec64 --- /dev/null +++ b/crates/external_services/src/file_storage.rs @@ -0,0 +1,96 @@ +//! +//! Module for managing file storage operations with support for multiple storage schemes. +//! + +use std::fmt::{Display, Formatter}; + +use common_utils::errors::CustomResult; + +/// Includes functionality for AWS S3 storage operations. +#[cfg(feature = "aws_s3")] +mod aws_s3; + +mod file_system; + +/// Enum representing different file storage configurations, allowing for multiple storage schemes. +#[derive(Debug, Clone, Default, serde::Deserialize)] +#[serde(tag = "file_storage_backend")] +#[serde(rename_all = "snake_case")] +pub enum FileStorageConfig { + /// AWS S3 storage configuration. + #[cfg(feature = "aws_s3")] + AwsS3 { + /// Configuration for AWS S3 file storage. + aws_s3: aws_s3::AwsFileStorageConfig, + }, + /// Local file system storage configuration. + #[default] + FileSystem, +} + +impl FileStorageConfig { + /// Validates the file storage configuration. + pub fn validate(&self) -> Result<(), InvalidFileStorageConfig> { + match self { + #[cfg(feature = "aws_s3")] + Self::AwsS3 { aws_s3 } => aws_s3.validate(), + Self::FileSystem => Ok(()), + } + } + + /// Retrieves the appropriate file storage client based on the file storage configuration. + pub async fn get_file_storage_client(&self) -> Box<dyn FileStorageInterface> { + match self { + #[cfg(feature = "aws_s3")] + Self::AwsS3 { aws_s3 } => Box::new(aws_s3::AwsFileStorageClient::new(aws_s3).await), + Self::FileSystem => Box::new(file_system::FileSystem), + } + } +} + +/// Trait for file storage operations +#[async_trait::async_trait] +pub trait FileStorageInterface: dyn_clone::DynClone + Sync + Send { + /// Uploads a file to the selected storage scheme. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError>; + + /// Deletes a file from the selected storage scheme. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError>; + + /// Retrieves a file from the selected storage scheme. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError>; +} + +dyn_clone::clone_trait_object!(FileStorageInterface); + +/// Error thrown when the file storage config is invalid +#[derive(Debug, Clone)] +pub struct InvalidFileStorageConfig(&'static str); + +impl std::error::Error for InvalidFileStorageConfig {} + +impl Display for InvalidFileStorageConfig { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "file_storage: {}", self.0) + } +} + +/// Represents errors that can occur during file storage operations. +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum FileStorageError { + /// Indicates that the file upload operation failed. + #[error("Failed to upload file")] + UploadFailed, + + /// Indicates that the file retrieval operation failed. + #[error("Failed to retrieve file")] + RetrieveFailed, + + /// Indicates that the file deletion operation failed. + #[error("Failed to delete file")] + DeleteFailed, +} diff --git a/crates/external_services/src/file_storage/aws_s3.rs b/crates/external_services/src/file_storage/aws_s3.rs new file mode 100644 index 00000000000..86d1c0f0efa --- /dev/null +++ b/crates/external_services/src/file_storage/aws_s3.rs @@ -0,0 +1,158 @@ +use aws_config::meta::region::RegionProviderChain; +use aws_sdk_s3::{ + operation::{ + delete_object::DeleteObjectError, get_object::GetObjectError, put_object::PutObjectError, + }, + Client, +}; +use aws_sdk_sts::config::Region; +use common_utils::{errors::CustomResult, ext_traits::ConfigExt}; +use error_stack::ResultExt; + +use super::InvalidFileStorageConfig; +use crate::file_storage::{FileStorageError, FileStorageInterface}; + +/// Configuration for AWS S3 file storage. +#[derive(Debug, serde::Deserialize, Clone, Default)] +#[serde(default)] +pub struct AwsFileStorageConfig { + /// The AWS region to send file uploads + region: String, + /// The AWS s3 bucket to send file uploads + bucket_name: String, +} + +impl AwsFileStorageConfig { + /// Validates the AWS S3 file storage configuration. + pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> { + use common_utils::fp_utils::when; + + when(self.region.is_default_or_empty(), || { + Err(InvalidFileStorageConfig("aws s3 region must not be empty")) + })?; + + when(self.bucket_name.is_default_or_empty(), || { + Err(InvalidFileStorageConfig( + "aws s3 bucket name must not be empty", + )) + }) + } +} + +/// AWS S3 file storage client. +#[derive(Debug, Clone)] +pub(super) struct AwsFileStorageClient { + /// AWS S3 client + inner_client: Client, + /// The name of the AWS S3 bucket. + bucket_name: String, +} + +impl AwsFileStorageClient { + /// Creates a new AWS S3 file storage client. + pub(super) async fn new(config: &AwsFileStorageConfig) -> Self { + let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone())); + let sdk_config = aws_config::from_env().region(region_provider).load().await; + Self { + inner_client: Client::new(&sdk_config), + bucket_name: config.bucket_name.clone(), + } + } + + /// Uploads a file to AWS S3. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), AwsS3StorageError> { + self.inner_client + .put_object() + .bucket(&self.bucket_name) + .key(file_key) + .body(file.into()) + .send() + .await + .map_err(AwsS3StorageError::UploadFailure)?; + Ok(()) + } + + /// Deletes a file from AWS S3. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), AwsS3StorageError> { + self.inner_client + .delete_object() + .bucket(&self.bucket_name) + .key(file_key) + .send() + .await + .map_err(AwsS3StorageError::DeleteFailure)?; + Ok(()) + } + + /// Retrieves a file from AWS S3. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, AwsS3StorageError> { + Ok(self + .inner_client + .get_object() + .bucket(&self.bucket_name) + .key(file_key) + .send() + .await + .map_err(AwsS3StorageError::RetrieveFailure)? + .body + .collect() + .await + .map_err(AwsS3StorageError::UnknownError)? + .to_vec()) + } +} + +#[async_trait::async_trait] +impl FileStorageInterface for AwsFileStorageClient { + /// Uploads a file to AWS S3. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError> { + self.upload_file(file_key, file) + .await + .change_context(FileStorageError::UploadFailed)?; + Ok(()) + } + + /// Deletes a file from AWS S3. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> { + self.delete_file(file_key) + .await + .change_context(FileStorageError::DeleteFailed)?; + Ok(()) + } + + /// Retrieves a file from AWS S3. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> { + Ok(self + .retrieve_file(file_key) + .await + .change_context(FileStorageError::RetrieveFailed)?) + } +} + +/// Enum representing errors that can occur during AWS S3 file storage operations. +#[derive(Debug, thiserror::Error)] +enum AwsS3StorageError { + /// Error indicating that file upload to S3 failed. + #[error("File upload to S3 failed: {0:?}")] + UploadFailure(aws_smithy_client::SdkError<PutObjectError>), + + /// Error indicating that file retrieval from S3 failed. + #[error("File retrieve from S3 failed: {0:?}")] + RetrieveFailure(aws_smithy_client::SdkError<GetObjectError>), + + /// Error indicating that file deletion from S3 failed. + #[error("File delete from S3 failed: {0:?}")] + DeleteFailure(aws_smithy_client::SdkError<DeleteObjectError>), + + /// Unknown error occurred. + #[error("Unknown error occurred: {0:?}")] + UnknownError(aws_sdk_s3::primitives::ByteStreamError), +} diff --git a/crates/external_services/src/file_storage/file_system.rs b/crates/external_services/src/file_storage/file_system.rs new file mode 100644 index 00000000000..15ca84deeb8 --- /dev/null +++ b/crates/external_services/src/file_storage/file_system.rs @@ -0,0 +1,144 @@ +//! +//! Module for local file system storage operations +//! + +use std::{ + fs::{remove_file, File}, + io::{Read, Write}, + path::PathBuf, +}; + +use common_utils::errors::CustomResult; +use error_stack::{IntoReport, ResultExt}; + +use crate::file_storage::{FileStorageError, FileStorageInterface}; + +/// Constructs the file path for a given file key within the file system. +/// The file path is generated based on the workspace path and the provided file key. +fn get_file_path(file_key: impl AsRef<str>) -> PathBuf { + let mut file_path = PathBuf::new(); + #[cfg(feature = "logs")] + file_path.push(router_env::env::workspace_path()); + #[cfg(not(feature = "logs"))] + file_path.push(std::env::current_dir().unwrap_or(".".into())); + + file_path.push("files"); + file_path.push(file_key.as_ref()); + file_path +} + +/// Represents a file system for storing and managing files locally. +#[derive(Debug, Clone)] +pub(super) struct FileSystem; + +impl FileSystem { + /// Saves the provided file data to the file system under the specified file key. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileSystemStorageError> { + let file_path = get_file_path(file_key); + + // Ignore the file name and create directories in the `file_path` if not exists + std::fs::create_dir_all( + file_path + .parent() + .ok_or(FileSystemStorageError::CreateDirFailed) + .into_report() + .attach_printable("Failed to obtain parent directory")?, + ) + .into_report() + .change_context(FileSystemStorageError::CreateDirFailed)?; + + let mut file_handler = File::create(file_path) + .into_report() + .change_context(FileSystemStorageError::CreateFailure)?; + file_handler + .write_all(&file) + .into_report() + .change_context(FileSystemStorageError::WriteFailure)?; + Ok(()) + } + + /// Deletes the file associated with the specified file key from the file system. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileSystemStorageError> { + let file_path = get_file_path(file_key); + remove_file(file_path) + .into_report() + .change_context(FileSystemStorageError::DeleteFailure)?; + Ok(()) + } + + /// Retrieves the file content associated with the specified file key from the file system. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileSystemStorageError> { + let mut received_data: Vec<u8> = Vec::new(); + let file_path = get_file_path(file_key); + let mut file = File::open(file_path) + .into_report() + .change_context(FileSystemStorageError::FileOpenFailure)?; + file.read_to_end(&mut received_data) + .into_report() + .change_context(FileSystemStorageError::ReadFailure)?; + Ok(received_data) + } +} + +#[async_trait::async_trait] +impl FileStorageInterface for FileSystem { + /// Saves the provided file data to the file system under the specified file key. + async fn upload_file( + &self, + file_key: &str, + file: Vec<u8>, + ) -> CustomResult<(), FileStorageError> { + self.upload_file(file_key, file) + .await + .change_context(FileStorageError::UploadFailed)?; + Ok(()) + } + + /// Deletes the file associated with the specified file key from the file system. + async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> { + self.delete_file(file_key) + .await + .change_context(FileStorageError::DeleteFailed)?; + Ok(()) + } + + /// Retrieves the file content associated with the specified file key from the file system. + async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> { + Ok(self + .retrieve_file(file_key) + .await + .change_context(FileStorageError::RetrieveFailed)?) + } +} + +/// Represents an error that can occur during local file system storage operations. +#[derive(Debug, thiserror::Error)] +enum FileSystemStorageError { + /// Error indicating opening a file failed + #[error("Failed while opening the file")] + FileOpenFailure, + + /// Error indicating file creation failed. + #[error("Failed to create file")] + CreateFailure, + + /// Error indicating reading a file failed. + #[error("Failed while reading the file")] + ReadFailure, + + /// Error indicating writing to a file failed. + #[error("Failed while writing into file")] + WriteFailure, + + /// Error indicating file deletion failed. + #[error("Failed while deleting the file")] + DeleteFailure, + + /// Error indicating directory creation failed + #[error("Failed while creating a directory")] + CreateDirFailed, +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index 9bf4916eec3..bba65873e91 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -9,6 +9,7 @@ pub mod email; #[cfg(feature = "kms")] pub mod kms; +pub mod file_storage; #[cfg(feature = "hashicorp-vault")] pub mod hashicorp_vault; diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e575daf7e7a..3d129edfe3f 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,10 +10,10 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] -aws_s3 = ["dep:aws-sdk-s3", "dep:aws-config"] -kms = ["external_services/kms", "dep:aws-config"] +aws_s3 = ["external_services/aws_s3"] +kms = ["external_services/kms"] hashicorp-vault = ["external_services/hashicorp-vault"] -email = ["external_services/email", "dep:aws-config", "olap"] +email = ["external_services/email", "olap"] frm = [] stripe = ["dep:serde_qs"] release = ["kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] @@ -42,8 +42,6 @@ actix-web = "4.3.1" async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" } argon2 = { version = "0.5.0", features = ["std"] } async-trait = "0.1.68" -aws-config = { version = "0.55.3", optional = true } -aws-sdk-s3 = { version = "0.28.0", optional = true } base64 = "0.21.2" bb8 = "0.8" bigdecimal = "0.3.1" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3c1d9f7d397..146a1ace28e 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -11,6 +11,7 @@ use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; #[cfg(feature = "email")] use external_services::email::EmailSettings; +use external_services::file_storage::FileStorageConfig; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; #[cfg(feature = "kms")] @@ -90,10 +91,9 @@ pub struct Settings { pub api_keys: ApiKeys, #[cfg(feature = "kms")] pub kms: kms::KmsConfig, + pub file_storage: FileStorageConfig, #[cfg(feature = "hashicorp-vault")] pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, - #[cfg(feature = "aws_s3")] - pub file_upload_config: FileUploadConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] @@ -721,16 +721,6 @@ pub struct ApiKeys { pub expiry_reminder_days: Vec<u8>, } -#[cfg(feature = "aws_s3")] -#[derive(Debug, Deserialize, Clone, Default)] -#[serde(default)] -pub struct FileUploadConfig { - /// The AWS region to send file uploads - pub region: String, - /// The AWS s3 bucket to send file uploads - pub bucket_name: String, -} - #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { #[serde(deserialize_with = "deser_to_get_connectors")] @@ -853,8 +843,11 @@ impl Settings { self.kms .validate() .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?; - #[cfg(feature = "aws_s3")] - self.file_upload_config.validate()?; + + self.file_storage + .validate() + .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; + self.lock_settings.validate()?; self.events.validate()?; Ok(()) diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 0b286ece843..910ae754347 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -127,25 +127,6 @@ impl super::settings::DrainerSettings { } } -#[cfg(feature = "aws_s3")] -impl super::settings::FileUploadConfig { - pub fn validate(&self) -> Result<(), ApplicationError> { - use common_utils::fp_utils::when; - - when(self.region.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "s3 region must not be empty".into(), - )) - })?; - - when(self.bucket_name.is_default_or_empty(), || { - Err(ApplicationError::InvalidConfigurationValueError( - "s3 bucket name must not be empty".into(), - )) - }) - } -} - impl super::settings::ApiKeys { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs index f3e56489806..d3f490a0a6c 100644 --- a/crates/router/src/core/files.rs +++ b/crates/router/src/core/files.rs @@ -1,9 +1,4 @@ pub mod helpers; -#[cfg(feature = "aws_s3")] -pub mod s3_utils; - -#[cfg(not(feature = "aws_s3"))] -pub mod fs_utils; use api_models::files; use error_stack::{IntoReport, ResultExt}; @@ -29,10 +24,7 @@ pub async fn files_create_core( ) .await?; let file_id = common_utils::generate_id(consts::ID_LENGTH, "file"); - #[cfg(feature = "aws_s3")] let file_key = format!("{}/{}", merchant_account.merchant_id, file_id); - #[cfg(not(feature = "aws_s3"))] - let file_key = format!("{}_{}", merchant_account.merchant_id, file_id); let file_new = diesel_models::file::FileMetadataNew { file_id: file_id.clone(), merchant_id: merchant_account.merchant_id.clone(), diff --git a/crates/router/src/core/files/fs_utils.rs b/crates/router/src/core/files/fs_utils.rs deleted file mode 100644 index 795f2fad759..00000000000 --- a/crates/router/src/core/files/fs_utils.rs +++ /dev/null @@ -1,57 +0,0 @@ -use std::{ - fs::{remove_file, File}, - io::{Read, Write}, - path::PathBuf, -}; - -use common_utils::errors::CustomResult; -use error_stack::{IntoReport, ResultExt}; - -use crate::{core::errors, env}; - -pub fn get_file_path(file_key: String) -> PathBuf { - let mut file_path = PathBuf::new(); - file_path.push(env::workspace_path()); - file_path.push("files"); - file_path.push(file_key); - file_path -} - -pub fn save_file_to_fs( - file_key: String, - file_data: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - let file_path = get_file_path(file_key); - let mut file = File::create(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to create file")?; - file.write_all(&file_data) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while writing into file")?; - Ok(()) -} - -pub fn delete_file_from_fs(file_key: String) -> CustomResult<(), errors::ApiErrorResponse> { - let file_path = get_file_path(file_key); - remove_file(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while deleting the file")?; - Ok(()) -} - -pub fn retrieve_file_from_fs(file_key: String) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - let mut received_data: Vec<u8> = Vec::new(); - let file_path = get_file_path(file_key); - let mut file = File::open(file_path) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while opening the file")?; - file.read_to_end(&mut received_data) - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while reading the file")?; - Ok(received_data) -} diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 9205d42aeee..0a509b238af 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -6,7 +6,7 @@ use futures::TryStreamExt; use crate::{ core::{ errors::{self, StorageErrorExt}, - files, payments, utils, + payments, utils, }, routes::AppState, services, @@ -30,37 +30,6 @@ pub async fn get_file_purpose(field: &mut Field) -> Option<api::FilePurpose> { } } -pub async fn upload_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, - file: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::upload_file_to_s3(state, file_key, file).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::save_file_to_fs(file_key, file); -} - -pub async fn delete_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, -) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::delete_file_from_s3(state, file_key).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::delete_file_from_fs(file_key); -} - -pub async fn retrieve_file( - #[cfg(feature = "aws_s3")] state: &AppState, - file_key: String, -) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - #[cfg(feature = "aws_s3")] - return files::s3_utils::retrieve_file_from_s3(state, file_key).await; - #[cfg(not(feature = "aws_s3"))] - return files::fs_utils::retrieve_file_from_fs(file_key); -} - pub async fn validate_file_upload( state: &AppState, merchant_account: domain::MerchantAccount, @@ -132,14 +101,11 @@ pub async fn delete_file_using_file_id( .attach_printable("File not available")?, }; match provider { - diesel_models::enums::FileUploadProvider::Router => { - delete_file( - #[cfg(feature = "aws_s3")] - state, - provider_file_id, - ) + diesel_models::enums::FileUploadProvider::Router => state + .file_storage_client + .delete_file(&provider_file_id) .await - } + .change_context(errors::ApiErrorResponse::InternalServerError), _ => Err(errors::ApiErrorResponse::FileProviderNotSupported { message: "Not Supported because provider is not Router".to_string(), } @@ -234,12 +200,11 @@ pub async fn retrieve_file_and_provider_file_id_from_file_id( match provider { diesel_models::enums::FileUploadProvider::Router => Ok(( Some( - retrieve_file( - #[cfg(feature = "aws_s3")] - state, - provider_file_id.clone(), - ) - .await?, + state + .file_storage_client + .retrieve_file(&provider_file_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?, ), Some(provider_file_id), )), @@ -364,13 +329,11 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id( payment_attempt.merchant_connector_id, )) } else { - upload_file( - #[cfg(feature = "aws_s3")] - state, - file_key.clone(), - create_file_request.file.clone(), - ) - .await?; + state + .file_storage_client + .upload_file(&file_key, create_file_request.file.clone()) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; Ok(( file_key, api_models::enums::FileUploadProvider::Router, diff --git a/crates/router/src/core/files/s3_utils.rs b/crates/router/src/core/files/s3_utils.rs deleted file mode 100644 index 228c23528cd..00000000000 --- a/crates/router/src/core/files/s3_utils.rs +++ /dev/null @@ -1,87 +0,0 @@ -use aws_config::{self, meta::region::RegionProviderChain}; -use aws_sdk_s3::{config::Region, Client}; -use common_utils::errors::CustomResult; -use error_stack::{IntoReport, ResultExt}; -use futures::TryStreamExt; - -use crate::{core::errors, routes}; - -async fn get_aws_client(state: &routes::AppState) -> Client { - let region_provider = - RegionProviderChain::first_try(Region::new(state.conf.file_upload_config.region.clone())); - let sdk_config = aws_config::from_env().region(region_provider).load().await; - Client::new(&sdk_config) -} - -pub async fn upload_file_to_s3( - state: &routes::AppState, - file_key: String, - file: Vec<u8>, -) -> CustomResult<(), errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Upload file to S3 - let upload_res = client - .put_object() - .bucket(bucket_name) - .key(file_key.clone()) - .body(file.into()) - .send() - .await; - upload_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File upload to S3 failed")?; - Ok(()) -} - -pub async fn delete_file_from_s3( - state: &routes::AppState, - file_key: String, -) -> CustomResult<(), errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Delete file from S3 - let delete_res = client - .delete_object() - .bucket(bucket_name) - .key(file_key) - .send() - .await; - delete_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File delete from S3 failed")?; - Ok(()) -} - -pub async fn retrieve_file_from_s3( - state: &routes::AppState, - file_key: String, -) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - let client = get_aws_client(state).await; - let bucket_name = &state.conf.file_upload_config.bucket_name; - // Get file data from S3 - let get_res = client - .get_object() - .bucket(bucket_name) - .key(file_key) - .send() - .await; - let mut object = get_res - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("File retrieve from S3 failed")?; - let mut received_data: Vec<u8> = Vec::new(); - while let Some(bytes) = object - .body - .try_next() - .await - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Invalid file data received from S3")? - { - received_data.extend_from_slice(&bytes); // Collect the bytes in the Vec - } - Ok(received_data) -} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f490cee8dab..2b26a5e7586 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -5,6 +5,7 @@ use actix_web::{web, Scope}; use analytics::AnalyticsConfig; #[cfg(feature = "email")] use external_services::email::{ses::AwsSes, EmailService}; +use external_services::file_storage::FileStorageInterface; #[cfg(all(feature = "olap", feature = "hashicorp-vault"))] use external_services::hashicorp_vault::decrypt::VaultFetch; #[cfg(feature = "kms")] @@ -68,6 +69,7 @@ pub struct AppState { #[cfg(feature = "olap")] pub pool: crate::analytics::AnalyticsProvider, pub request_id: Option<RequestId>, + pub file_storage_client: Box<dyn FileStorageInterface>, } impl scheduler::SchedulerAppState for AppState { @@ -266,6 +268,8 @@ impl AppState { #[cfg(feature = "email")] let email_client = Arc::new(create_email_client(&conf).await); + let file_storage_client = conf.file_storage.get_file_storage_client().await; + Self { flow_name: String::from("default"), store, @@ -279,6 +283,7 @@ impl AppState { #[cfg(feature = "olap")] pool, request_id: None, + file_storage_client, } }) .await diff --git a/docker-compose.yml b/docker-compose.yml index 3839269a522..e55008f1e34 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -54,6 +54,7 @@ services: - router_net volumes: - ./config:/local/config + - ./files:/local/bin/files labels: logs: "promtail" healthcheck:
2024-01-14T14:27:35Z
## Description <!-- Describe your changes in detail --> This PR includes refactoring for: * Enabling easy extension of other file storage schemes. * Providing a runtime flag for the file storage feature. * Restrict the file storage objects(structs, methods) visibility wherever possible. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #3338, Closes #3347 # ### File System 1. File uploading ``` curl --location --request POST 'localhost:8080/files' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' \ --header 'Content-Type: multipart/form-data; boundary=6467930559a8e09e-babf866111649afb-06f42165ce9a45a7-bc825186544537e1' \ --header 'Accept-Encoding: gzip' \ --form 'purpose="dispute_evidence"' \ --form 'file=@"/Users/sai.harsha/Desktop/dummy.pdf"' \ --form 'dispute_id="dp_Hv9m2MJGRjptYmEYPqFa"' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/ddec5aff-a0e3-4d09-9d0d-32f698e0c3cc) 2. File retrieve ``` curl --location --request GET 'localhost:8080/files/file_qXP0X6uAgLwSvswj8T41' \ --header 'Accept: application/json' \ --header 'api-key: dev_H3Uf7cssLge9XnWZZfV2M5xwqroMHt46cXh0EwXJQHTdYuBTVC3KVnA5Fo45hagw' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/efe193e3-b5d7-4f30-8546-c499a6c36483) 3. File delete ``` curl --location --request DELETE 'localhost:8080/files/file_z4giuhfczJqbXwNhazqS' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/a724d0b7-1c80-4c62-9b2e-2fd20205c681) ### Aws S3 1. File uploading ![image](https://github.com/juspay/hyperswitch/assets/70657455/e4077964-e117-4f50-8e9b-25bdcb794a9a) 2. File retrieve ![image](https://github.com/juspay/hyperswitch/assets/70657455/b7d3e799-0fde-48a2-aac0-513faa49523e) 3. File delete ![image (1)](https://github.com/juspay/hyperswitch/assets/70657455/e398faeb-0697-483c-8a41-dd5bd47d5e18)
3fbffdc242dafe7983c542573b7c6362f99331e6
* Create a dispute and get the `dispute_id` ### File System 1. File uploading ``` curl --location --request POST 'localhost:8080/files' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' \ --header 'Content-Type: multipart/form-data; boundary=6467930559a8e09e-babf866111649afb-06f42165ce9a45a7-bc825186544537e1' \ --header 'Accept-Encoding: gzip' \ --form 'purpose="dispute_evidence"' \ --form 'file=@"/Users/sai.harsha/Desktop/dummy.pdf"' \ --form 'dispute_id="dp_Hv9m2MJGRjptYmEYPqFa"' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/ddec5aff-a0e3-4d09-9d0d-32f698e0c3cc) 2. File retrieve ``` curl --location --request GET 'localhost:8080/files/file_qXP0X6uAgLwSvswj8T41' \ --header 'Accept: application/json' \ --header 'api-key: dev_H3Uf7cssLge9XnWZZfV2M5xwqroMHt46cXh0EwXJQHTdYuBTVC3KVnA5Fo45hagw' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/efe193e3-b5d7-4f30-8546-c499a6c36483) 3. File delete ``` curl --location --request DELETE 'localhost:8080/files/file_z4giuhfczJqbXwNhazqS' \ --header 'Accept: application/json' \ --header 'api-key: dev_vbE0ODzAkDHFkW2FFQZEAU4VeSk5ij4kWOZl2JXqRtYf50rVqxefvSofYCqre89Q' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/a724d0b7-1c80-4c62-9b2e-2fd20205c681) ### Aws S3 1. File uploading ![image](https://github.com/juspay/hyperswitch/assets/70657455/e4077964-e117-4f50-8e9b-25bdcb794a9a) 2. File retrieve ![image](https://github.com/juspay/hyperswitch/assets/70657455/b7d3e799-0fde-48a2-aac0-513faa49523e) 3. File delete ![image (1)](https://github.com/juspay/hyperswitch/assets/70657455/e398faeb-0697-483c-8a41-dd5bd47d5e18)
[ "Cargo.lock", "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/external_services/Cargo.toml", "crates/external_services/src/file_storage.rs", "crates/external_services/src/file_storage/aws_s3.rs", "crates/external_services/src/file_storage/file_system.rs",...
juspay/hyperswitch
juspay__hyperswitch-3359
Bug: [FEATURE] Recon APIs ### Feature Description Add recon related APIs in HyperSwitch for managing recon module for the consumers. Recon dashboard is a separate application hosted at https://sandbox.hyperswitch.io/recon-dashboard/ Recon module in HyperSwitch should be able to perform below tasks - Toggle recon module for a given merchant - Generate tokens for Recon dashboard login - Let admins modify the state of recon related stuff for a given merchant - Verify the generated token ### Possible Implementation Below endpoints are exposed for performing the required tasks - `/recon/update_merchant` - admin API call for updating any recon related field for a given merchant. - `/recon/token` - request a token for an user which is used for logging into Recon's dashboard. - `/recon/request` - let's user send a mail to HS team for enabling recon for their merchant's account. - `/recon/verify_token` - validate a generated token. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 69980361500..45702a4ecb0 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" license.workspace = true [features] -default = ["payouts", "frm"] +default = ["payouts", "frm", "recon"] business_profile_routing = [] connector_choice_bcompat = [] errors = ["dep:actix-web", "dep:reqwest"] @@ -18,6 +18,7 @@ dummy_connector = ["euclid/dummy_connector", "common_enums/dummy_connector"] detailed_errors = [] payouts = [] frm = [] +recon = [] [dependencies] actix-web = { version = "4.3.1", optional = true } diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 6d9bd5db342..26a9d222d6b 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -5,6 +5,8 @@ mod locker_migration; pub mod payment; #[cfg(feature = "payouts")] pub mod payouts; +#[cfg(feature = "recon")] +pub mod recon; pub mod refund; pub mod routing; pub mod user; diff --git a/crates/api_models/src/events/recon.rs b/crates/api_models/src/events/recon.rs new file mode 100644 index 00000000000..aed648f4c86 --- /dev/null +++ b/crates/api_models/src/events/recon.rs @@ -0,0 +1,21 @@ +use common_utils::events::{ApiEventMetric, ApiEventsType}; + +use crate::recon::{ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest}; + +impl ApiEventMetric for ReconUpdateMerchantRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Recon) + } +} + +impl ApiEventMetric for ReconTokenResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Recon) + } +} + +impl ApiEventMetric for ReconStatusResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Recon) + } +} diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 1f4cb7359c7..c0743c8b8fc 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -1,7 +1,11 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; +#[cfg(feature = "recon")] +use masking::PeekInterface; #[cfg(feature = "dummy_connector")] use crate::user::sample_data::SampleDataRequest; +#[cfg(feature = "recon")] +use crate::user::VerifyTokenResponse; use crate::user::{ dashboard_metadata::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, @@ -21,6 +25,16 @@ impl ApiEventMetric for DashboardEntryResponse { } } +#[cfg(feature = "recon")] +impl ApiEventMetric for VerifyTokenResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::User { + merchant_id: self.merchant_id.clone(), + user_id: self.user_email.peek().to_string(), + }) + } +} + common_utils::impl_misc_api_event_type!( SignUpRequest, SignUpWithMerchantIdRequest, diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index dc1f6eb6537..1ea79ff6fe8 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -26,6 +26,8 @@ pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod pm_auth; +#[cfg(feature = "recon")] +pub mod recon; pub mod refunds; pub mod routing; pub mod surcharge_decision_configs; diff --git a/crates/api_models/src/recon.rs b/crates/api_models/src/recon.rs new file mode 100644 index 00000000000..efbe28f96ba --- /dev/null +++ b/crates/api_models/src/recon.rs @@ -0,0 +1,21 @@ +use common_utils::pii; +use masking::Secret; + +use crate::enums; + +#[derive(serde::Deserialize, Debug, serde::Serialize)] +pub struct ReconUpdateMerchantRequest { + pub merchant_id: String, + pub recon_status: enums::ReconStatus, + pub user_email: pii::Email, +} + +#[derive(Debug, serde::Serialize)] +pub struct ReconTokenResponse { + pub token: Secret<String>, +} + +#[derive(Debug, serde::Serialize)] +pub struct ReconStatusResponse { + pub recon_status: enums::ReconStatus, +} diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index f5af31c8e7f..a04c4fef660 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -140,3 +140,10 @@ pub struct UserMerchantAccount { pub merchant_id: String, pub merchant_name: OptionalEncryptableName, } + +#[cfg(feature = "recon")] +#[derive(serde::Serialize, Debug)] +pub struct VerifyTokenResponse { + pub merchant_id: String, + pub user_email: pii::Email, +} diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 6bbf78afe42..c2bf50d96c3 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -49,6 +49,7 @@ pub enum ApiEventsType { Miscellaneous, RustLocker, FraudCheck, + Recon, } impl ApiEventMetric for serde_json::Value {} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 8ecac362091..0a544e0bd09 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -9,7 +9,7 @@ readme = "README.md" license.workspace = true [features] -default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] +default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm", "recon"] s3 = ["dep:aws-sdk-s3", "dep:aws-config"] kms = ["external_services/kms", "dep:aws-config"] email = ["external_services/email", "dep:aws-config", "olap"] @@ -30,6 +30,7 @@ connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connect external_access_dc = ["dummy_connector"] detailed_errors = ["api_models/detailed_errors", "error-stack/serde"] payouts = [] +recon = ["email"] retry = [] [dependencies] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index b1a582cedec..27a4f67618e 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -757,3 +757,32 @@ pub async fn send_verification_mail( Ok(ApplicationResponse::StatusOk) } + +#[cfg(feature = "recon")] +pub async fn verify_token( + state: AppState, + req: auth::ReconUser, +) -> UserResponse<user_api::VerifyTokenResponse> { + let user = state + .store + .find_user_by_id(&req.user_id) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(UserErrors::UserNotFound) + } else { + e.change_context(UserErrors::InternalServerError) + } + })?; + let merchant_id = state + .store + .find_user_role_by_user_id(&req.user_id) + .await + .change_context(UserErrors::InternalServerError)? + .merchant_id; + + Ok(ApplicationResponse::Json(user_api::VerifyTokenResponse { + merchant_id: merchant_id.to_string(), + user_email: user.email, + })) +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 696198f2153..c38a4dc85b5 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -165,6 +165,12 @@ pub fn mk_app( { server_app = server_app.service(routes::StripeApis::server(state.clone())); } + + #[cfg(feature = "recon")] + { + server_app = server_app.service(routes::Recon::server(state.clone())); + } + server_app = server_app.service(routes::Cards::server(state.clone())); server_app = server_app.service(routes::Cache::server(state.clone())); server_app = server_app.service(routes::Health::server(state)); diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index d4bfabb6f92..d9916f98e74 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -28,6 +28,8 @@ pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; +#[cfg(feature = "recon")] +pub mod recon; pub mod refunds; #[cfg(feature = "olap")] pub mod routing; @@ -53,6 +55,8 @@ pub use self::app::DummyConnector; pub use self::app::Forex; #[cfg(feature = "payouts")] pub use self::app::Payouts; +#[cfg(all(feature = "olap", feature = "recon"))] +pub use self::app::Recon; #[cfg(all(feature = "olap", feature = "kms"))] pub use self::app::Verify; pub use self::app::{ diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 77253d1d75c..0c489dbe63a 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -40,6 +40,8 @@ use super::{configs::*, customers::*, mandates::*, payments::*, refunds::*}; use super::{ephemeral_key::*, payment_methods::*, webhooks::*}; #[cfg(all(feature = "frm", feature = "oltp"))] use crate::routes::fraud_check as frm_routes; +#[cfg(all(feature = "recon", feature = "olap"))] +use crate::routes::recon as recon_routes; #[cfg(feature = "olap")] use crate::routes::verify_connector::payment_connector_verify; pub use crate::{ @@ -568,6 +570,26 @@ impl PaymentMethods { } } +#[cfg(all(feature = "olap", feature = "recon"))] +pub struct Recon; + +#[cfg(all(feature = "olap", feature = "recon"))] +impl Recon { + pub fn server(state: AppState) -> Scope { + web::scope("/recon") + .app_data(web::Data::new(state)) + .service( + web::resource("/update_merchant") + .route(web::post().to(recon_routes::update_merchant)), + ) + .service(web::resource("/token").route(web::get().to(recon_routes::get_recon_token))) + .service( + web::resource("/request").route(web::post().to(recon_routes::request_for_recon)), + ) + .service(web::resource("/verify_token").route(web::get().to(verify_recon_token))) + } +} + #[cfg(feature = "olap")] pub struct Blocklist; diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index c560f0d988a..12cf76be475 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -31,6 +31,7 @@ pub enum ApiIdentifier { User, UserRole, ConnectorOnboarding, + Recon, } impl From<Flow> for ApiIdentifier { @@ -186,6 +187,11 @@ impl From<Flow> for ApiIdentifier { Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { Self::ConnectorOnboarding } + + Flow::ReconMerchantUpdate + | Flow::ReconTokenRequest + | Flow::ReconServiceRequest + | Flow::ReconVerifyToken => Self::Recon, } } } diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs new file mode 100644 index 00000000000..d34e30237dd --- /dev/null +++ b/crates/router/src/routes/recon.rs @@ -0,0 +1,250 @@ +use actix_web::{web, HttpRequest, HttpResponse}; +use api_models::recon as recon_api; +use common_enums::ReconStatus; +use error_stack::ResultExt; +use masking::{ExposeInterface, PeekInterface, Secret}; +use router_env::Flow; + +use super::AppState; +use crate::{ + core::{ + api_locking, + errors::{self, RouterResponse, RouterResult, StorageErrorExt, UserErrors}, + }, + services::{ + api as service_api, api, + authentication::{self as auth, ReconUser, UserFromToken}, + email::types as email_types, + recon::ReconToken, + }, + types::{ + api::{self as api_types, enums}, + domain::{UserEmail, UserFromStorage, UserName}, + storage, + }, +}; + +pub async fn update_merchant( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<recon_api::ReconUpdateMerchantRequest>, +) -> HttpResponse { + let flow = Flow::ReconMerchantUpdate; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _user, req| recon_merchant_account_update(state, req), + &auth::ReconAdmin, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { + let flow = Flow::ReconServiceRequest; + Box::pin(api::server_wrap( + flow, + state, + &http_req, + (), + |state, user: UserFromToken, _req| send_recon_request(state, user), + &auth::DashboardNoPermissionAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { + let flow = Flow::ReconTokenRequest; + Box::pin(api::server_wrap( + flow, + state, + &req, + (), + |state, user: ReconUser, _| generate_recon_token(state, user), + &auth::ReconJWT, + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn send_recon_request( + state: AppState, + user: UserFromToken, +) -> RouterResponse<recon_api::ReconStatusResponse> { + let db = &*state.store; + let user_from_db = db + .find_user_by_id(&user.user_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let merchant_id = db + .find_user_role_by_user_id(&user.user_id) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)? + .merchant_id; + let key_store = db + .get_merchant_key_store_by_merchant_id( + merchant_id.as_str(), + &db.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + let merchant_account = db + .find_merchant_account_by_merchant_id(merchant_id.as_str(), &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let email_contents = email_types::ProFeatureRequest { + feature_name: "RECONCILIATION & SETTLEMENT".to_string(), + merchant_id: merchant_id.clone(), + user_name: UserName::new(user_from_db.name) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to form username")?, + recipient_email: UserEmail::from_pii_email(user_from_db.email.clone()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert to UserEmail from pii::Email")?, + settings: state.conf.clone(), + subject: format!( + "Dashboard Pro Feature Request by {}", + user_from_db.email.expose().peek() + ), + }; + + let is_email_sent = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to compose and send email for ProFeatureRequest") + .is_ok(); + + if is_email_sent { + let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { + recon_status: enums::ReconStatus::Requested, + }; + + let response = db + .update_merchant(merchant_account, updated_merchant_account, &key_store) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!("Failed while updating merchant's recon status: {merchant_id}") + })?; + + Ok(service_api::ApplicationResponse::Json( + recon_api::ReconStatusResponse { + recon_status: response.recon_status, + }, + )) + } else { + Ok(service_api::ApplicationResponse::Json( + recon_api::ReconStatusResponse { + recon_status: enums::ReconStatus::NotRequested, + }, + )) + } +} + +pub async fn recon_merchant_account_update( + state: AppState, + req: recon_api::ReconUpdateMerchantRequest, +) -> RouterResponse<api_types::MerchantAccountResponse> { + let merchant_id = &req.merchant_id.clone(); + let user_email = &req.user_email.clone(); + + let db = &*state.store; + + let key_store = db + .get_merchant_key_store_by_merchant_id( + &req.merchant_id, + &db.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let merchant_account = db + .find_merchant_account_by_merchant_id(merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { + recon_status: req.recon_status, + }; + + let response = db + .update_merchant(merchant_account, updated_merchant_account, &key_store) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!("Failed while updating merchant's recon status: {merchant_id}") + })?; + + let email_contents = email_types::ReconActivation { + recipient_email: UserEmail::from_pii_email(user_email.clone()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert to UserEmail from pii::Email")?, + user_name: UserName::new(Secret::new("HyperSwitch User".to_string())) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to form username")?, + settings: state.conf.clone(), + subject: "Approval of Recon Request - Access Granted to Recon Dashboard", + }; + + if req.recon_status == ReconStatus::Active { + let _is_email_sent = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to compose and send email for ReconActivation") + .is_ok(); + } + + Ok(service_api::ApplicationResponse::Json( + response + .try_into() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "merchant_account", + })?, + )) +} + +pub async fn generate_recon_token( + state: AppState, + req: ReconUser, +) -> RouterResponse<recon_api::ReconTokenResponse> { + let db = &*state.store; + let user = db + .find_user_by_id(&req.user_id) + .await + .map_err(|e| { + if e.current_context().is_db_not_found() { + e.change_context(errors::ApiErrorResponse::InvalidJwtToken) + } else { + e.change_context(errors::ApiErrorResponse::InternalServerError) + } + })? + .into(); + + let token = Box::pin(get_recon_auth_token(user, state)) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + Ok(service_api::ApplicationResponse::Json( + recon_api::ReconTokenResponse { token }, + )) +} + +pub async fn get_recon_auth_token( + user: UserFromStorage, + state: AppState, +) -> RouterResult<Secret<String>> { + ReconToken::new_token(user.0.user_id.clone(), &state.conf).await +} diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index a77b82c550e..976fd5c9f56 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -388,3 +388,18 @@ pub async fn verify_email_request( )) .await } + +#[cfg(feature = "recon")] +pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse { + let flow = Flow::ReconVerifyToken; + Box::pin(api::server_wrap( + flow, + state.clone(), + &http_req, + (), + |state, user, _req| user_core::verify_token(state, user), + &auth::ReconJWT, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 57f3b802bd5..8c973105d53 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -7,6 +7,8 @@ pub mod jwt; pub mod kafka; pub mod logger; pub mod pm_auth; +#[cfg(feature = "recon")] +pub mod recon; #[cfg(feature = "email")] pub mod email; diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index b48465ebd17..3370912394e 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -12,10 +12,14 @@ use serde::Serialize; use super::authorization::{self, permissions::Permission}; #[cfg(feature = "olap")] use super::jwt; +#[cfg(feature = "recon")] +use super::recon::ReconToken; #[cfg(feature = "olap")] use crate::consts; #[cfg(feature = "olap")] use crate::core::errors::UserResult; +#[cfg(feature = "recon")] +use crate::routes::AppState; use crate::{ configs::settings, core::{ @@ -822,3 +826,95 @@ where } default_auth } + +#[cfg(feature = "recon")] +static RECON_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = + tokio::sync::OnceCell::const_new(); + +#[cfg(feature = "recon")] +pub async fn get_recon_admin_api_key( + secrets: &settings::Secrets, + #[cfg(feature = "kms")] kms_client: &kms::KmsClient, +) -> RouterResult<&'static StrongSecret<String>> { + RECON_API_KEY + .get_or_try_init(|| async { + #[cfg(feature = "kms")] + let recon_admin_api_key = secrets + .kms_encrypted_recon_admin_api_key + .decrypt_inner(kms_client) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to KMS decrypt recon admin API key")?; + + #[cfg(not(feature = "kms"))] + let recon_admin_api_key = secrets.recon_admin_api_key.clone(); + + Ok(StrongSecret::new(recon_admin_api_key)) + }) + .await +} + +#[cfg(feature = "recon")] +pub struct ReconAdmin; + +#[async_trait] +#[cfg(feature = "recon")] +impl<A> AuthenticateAndFetch<(), A> for ReconAdmin +where + A: AppStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<((), AuthenticationType)> { + let request_admin_api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + let conf = state.conf(); + + let admin_api_key = get_recon_admin_api_key( + &conf.secrets, + #[cfg(feature = "kms")] + kms::get_kms_client(&conf.kms).await, + ) + .await?; + + if request_admin_api_key != admin_api_key.peek() { + Err(report!(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Recon Admin Authentication Failure"))?; + } + + Ok(((), AuthenticationType::NoAuth)) + } +} + +#[cfg(feature = "recon")] +pub struct ReconJWT; +#[cfg(feature = "recon")] +pub struct ReconUser { + pub user_id: String, +} +#[cfg(feature = "recon")] +impl AuthInfo for ReconUser { + fn get_merchant_id(&self) -> Option<&str> { + None + } +} +#[cfg(all(feature = "olap", feature = "recon"))] +#[async_trait] +impl AuthenticateAndFetch<ReconUser, AppState> for ReconJWT { + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &AppState, + ) -> RouterResult<(ReconUser, AuthenticationType)> { + let payload = parse_jwt_payload::<AppState, ReconToken>(request_headers, state).await?; + + Ok(( + ReconUser { + user_id: payload.user_id, + }, + AuthenticationType::NoAuth, + )) + } +} diff --git a/crates/router/src/services/email/assets/recon_activated.html b/crates/router/src/services/email/assets/recon_activation.html similarity index 100% rename from crates/router/src/services/email/assets/recon_activated.html rename to crates/router/src/services/email/assets/recon_activation.html diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index d5c28b1fd6a..0ef15eaa40d 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,17 +1,37 @@ use common_utils::errors::CustomResult; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; -use masking::ExposeInterface; +use masking::{ExposeInterface, PeekInterface}; use crate::{configs, consts}; #[cfg(feature = "olap")] use crate::{core::errors::UserErrors, services::jwt, types::domain}; pub enum EmailBody { - Verify { link: String }, - Reset { link: String, user_name: String }, - MagicLink { link: String, user_name: String }, - InviteUser { link: String, user_name: String }, + Verify { + link: String, + }, + Reset { + link: String, + user_name: String, + }, + MagicLink { + link: String, + user_name: String, + }, + InviteUser { + link: String, + user_name: String, + }, + ReconActivation { + user_name: String, + }, + ProFeatureRequest { + feature_name: String, + merchant_id: String, + user_name: String, + user_email: String, + }, } pub mod html { @@ -43,6 +63,30 @@ pub mod html { link = link ) } + EmailBody::ReconActivation { user_name } => { + format!( + include_str!("assets/recon_activation.html"), + username = user_name, + ) + } + EmailBody::ProFeatureRequest { + feature_name, + merchant_id, + user_name, + user_email, + } => { + format!( + "Dear Hyperswitch Support Team, + + Dashboard Pro Feature Request, + Feature name : {feature_name} + Merchant ID : {merchant_id} + Merchant Name : {user_name} + Email : {user_email} + + (note: This is an auto generated email. use merchant email for any further comunications)", + ) + } } } } @@ -198,3 +242,54 @@ impl EmailData for InviteUser { }) } } + +pub struct ReconActivation { + pub recipient_email: domain::UserEmail, + pub user_name: domain::UserName, + pub settings: std::sync::Arc<configs::settings::Settings>, + pub subject: &'static str, +} + +#[async_trait::async_trait] +impl EmailData for ReconActivation { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let body = html::get_html_body(EmailBody::ReconActivation { + user_name: self.user_name.clone().get_secret().expose(), + }); + + Ok(EmailContents { + subject: self.subject.to_string(), + body: external_services::email::IntermediateString::new(body), + recipient: self.recipient_email.clone().into_inner(), + }) + } +} + +pub struct ProFeatureRequest { + pub recipient_email: domain::UserEmail, + pub feature_name: String, + pub merchant_id: String, + pub user_name: domain::UserName, + pub settings: std::sync::Arc<configs::settings::Settings>, + pub subject: String, +} + +#[async_trait::async_trait] +impl EmailData for ProFeatureRequest { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let recipient = self.recipient_email.clone().into_inner(); + + let body = html::get_html_body(EmailBody::ProFeatureRequest { + user_name: self.user_name.clone().get_secret().expose(), + feature_name: self.feature_name.clone(), + merchant_id: self.merchant_id.clone(), + user_email: recipient.peek().to_string(), + }); + + Ok(EmailContents { + subject: self.subject.clone(), + body: external_services::email::IntermediateString::new(body), + recipient, + }) + } +} diff --git a/crates/router/src/services/recon.rs b/crates/router/src/services/recon.rs new file mode 100644 index 00000000000..d5a2151a487 --- /dev/null +++ b/crates/router/src/services/recon.rs @@ -0,0 +1,29 @@ +use error_stack::ResultExt; +use masking::Secret; + +use super::jwt; +use crate::{ + consts, + core::{self, errors::RouterResult}, + routes::app::settings::Settings, +}; + +#[derive(serde::Serialize, serde::Deserialize)] +pub struct ReconToken { + pub user_id: String, + pub exp: u64, +} + +impl ReconToken { + pub async fn new_token(user_id: String, settings: &Settings) -> RouterResult<Secret<String>> { + let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); + let exp = jwt::generate_exp(exp_duration) + .change_context(core::errors::ApiErrorResponse::InternalServerError)? + .as_secs(); + let token_payload = Self { user_id, exp }; + let token = jwt::generate_jwt(&token_payload, settings) + .await + .change_context(core::errors::ApiErrorResponse::InternalServerError)?; + Ok(Secret::new(token)) + } +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 8f0b9bad3e8..0d6636e567d 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -165,6 +165,14 @@ pub enum Flow { RefundsList, // Retrieve forex flow. RetrieveForexFlow, + /// Toggles recon service for a merchant. + ReconMerchantUpdate, + /// Recon token request flow. + ReconTokenRequest, + /// Initial request for recon service. + ReconServiceRequest, + /// Recon token verification flow + ReconVerifyToken, /// Routing create flow, RoutingCreateConfig, /// Routing link config
2024-01-12T15:28:13Z
## Description This PR adds recon APIs for activating recon as a feature on HyperSwitch dashboard and generating tokens for Recon dashboard. Issue - #3359 ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
58cc8d6109ce49d385b06c762ab3f6670f5094eb
Tested below endpoints for Recon service using the attached postman collection. Postman collection - https://galactic-capsule-229427.postman.co/workspace/My-Workspace~2b563e0d-bad3-420f-8c0b-0fd5b278a4fe/collection/9906252-4ef01bc4-53d4-40c0-a3e7-c84c8e32f105?action=share&creator=9906252 **Endpoints** 1. `/recon/update_merchant` - admin API call for updating any recon related field for a given merchant. 2. `/recon/token` - request a token for an user which is used for logging into Recon's dashboard. 3. `/recon/request` - let's user send a mail to HS team for enabling recon for their merchant's account. 4. `/recon/verify_token` - validate a generated token.
[ "crates/api_models/Cargo.toml", "crates/api_models/src/events.rs", "crates/api_models/src/events/recon.rs", "crates/api_models/src/events/user.rs", "crates/api_models/src/lib.rs", "crates/api_models/src/recon.rs", "crates/api_models/src/user.rs", "crates/common_utils/src/events.rs", "crates/router/C...
juspay/hyperswitch
juspay__hyperswitch-3342
Bug: [FEATURE] [Bankofamerica] Add 3DS flow for cards ### Feature Description Add 3DS flow for cards for connector BankOfAmerica. ### Possible Implementation Add 3DS flow for cards for connector BankOfAmerica. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index e20f9c1b65d..d4e11964192 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -351,6 +351,7 @@ stripe = { payment_method = "bank_transfer" } nuvei = { payment_method = "card" } shift4 = { payment_method = "card" } bluesnap = { payment_method = "card" } +bankofamerica = {payment_method = "card"} cybersource = {payment_method = "card"} nmi = {payment_method = "card"} diff --git a/config/development.toml b/config/development.toml index 5732d5f0d1d..91269005a0f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -428,6 +428,7 @@ stripe = {payment_method = "bank_transfer"} nuvei = {payment_method = "card"} shift4 = {payment_method = "card"} bluesnap = {payment_method = "card"} +bankofamerica = {payment_method = "card"} cybersource = {payment_method = "card"} nmi = {payment_method = "card"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index c6934a64671..450fe106a31 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -241,6 +241,7 @@ stripe = {payment_method = "bank_transfer"} nuvei = {payment_method = "card"} shift4 = {payment_method = "card"} bluesnap = {payment_method = "card"} +bankofamerica = {payment_method = "card"} cybersource = {payment_method = "card"} nmi = {payment_method = "card"} diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs index aeb3dafcfa2..0d901b99078 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -12,6 +12,7 @@ use time::OffsetDateTime; use transformers as bankofamerica; use url::Url; +use super::utils::{PaymentsAuthorizeRequestData, RouterData}; use crate::{ configs::settings, connector::{utils as connector_utils, utils::RefundsRequestData}, @@ -48,6 +49,8 @@ impl api::Refund for Bankofamerica {} impl api::RefundExecute for Bankofamerica {} impl api::RefundSync for Bankofamerica {} impl api::PaymentToken for Bankofamerica {} +impl api::PaymentsPreProcessing for Bankofamerica {} +impl api::PaymentsCompleteAuthorize for Bankofamerica {} impl Bankofamerica { pub fn generate_digest(&self, payload: &[u8]) -> String { @@ -299,6 +302,113 @@ impl } } +impl + ConnectorIntegration< + api::PreProcessing, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + > for Bankofamerica +{ + fn get_headers( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let redirect_response = req.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => Ok(format!( + "{}risk/v1/authentications", + self.base_url(connectors) + )), + Some(_) | None => Ok(format!( + "{}risk/v1/authentication-results", + self.base_url(connectors) + )), + } + } + fn get_request_body( + &self, + req: &types::PaymentsPreProcessingRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = bankofamerica::BankOfAmericaRouterData::try_from(( + &self.get_currency_unit(), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + req.request + .amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "amount", + })?, + req, + ))?; + let connector_req = + bankofamerica::BankOfAmericaPreProcessingRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsPreProcessingType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPreProcessingType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPreProcessingType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsPreProcessingRouterData, + res: Response, + ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { + let response: bankofamerica::BankOfAmericaPreProcessingResponse = res + .response + .parse_struct("BankOfAmerica AuthEnrollmentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Bankofamerica { @@ -316,13 +426,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}pts/v2/payments/", - api::ConnectorCommon::base_url(self, connectors) - )) + if req.is_three_ds() && req.request.is_card() { + Ok(format!( + "{}risk/v1/authentication-setups", + self.base_url(connectors) + )) + } else { + Ok(format!("{}pts/v2/payments/", self.base_url(connectors))) + } } fn get_request_body( @@ -336,9 +450,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req.request.amount, req, ))?; - let connector_req = - bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + if req.is_three_ds() && req.request.is_card() { + let connector_req = + bankofamerica::BankOfAmericaAuthSetupRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } else { + let connector_req = + bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } } fn build_request( @@ -368,6 +488,130 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + if data.is_three_ds() && data.request.is_card() { + let response: bankofamerica::BankOfAmericaAuthSetupResponse = res + .response + .parse_struct("Bankofamerica AuthSetupResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } else { + let response: bankofamerica::BankOfAmericaPaymentsResponse = res + .response + .parse_struct("Bankofamerica PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + } + + fn get_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } + + fn get_5xx_error_response( + &self, + res: Response, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + let response: bankofamerica::BankOfAmericaServerErrorResponse = res + .response + .parse_struct("BankOfAmericaServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let attempt_status = match response.reason { + Some(reason) => match reason { + transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), + transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, + }, + None => None, + }; + Ok(ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + attempt_status, + connector_transaction_id: None, + }) + } +} + +impl + ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Bankofamerica +{ + fn get_headers( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + _req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}pts/v2/payments/", self.base_url(connectors))) + } + fn get_request_body( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = bankofamerica::BankOfAmericaRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = + bankofamerica::BankOfAmericaPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCompleteAuthorizeRouterData, + res: Response, + ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: bankofamerica::BankOfAmericaPaymentsResponse = res .response .parse_struct("BankOfAmerica PaymentResponse") diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 6abe1b634df..72e3de0bf77 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1,6 +1,7 @@ use api_models::payments; use base64::Engine; -use common_utils::pii; +use common_utils::{ext_traits::ValueExt, pii}; +use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -8,10 +9,12 @@ use serde_json::Value; use crate::{ connector::utils::{ self, AddressDetailsData, ApplePayDecrypt, CardData, CardIssuer, - PaymentsAuthorizeRequestData, PaymentsSyncRequestData, RouterData, + PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + PaymentsPreProcessingData, PaymentsSyncRequestData, RouterData, }, consts, core::errors, + services, types::{ self, api::{self, enums as api_enums}, @@ -85,14 +88,17 @@ pub struct BankOfAmericaPaymentsRequest { order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] + consumer_authentication_information: Option<BankOfAmericaConsumerAuthInformation>, + #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ProcessingInformation { - capture: bool, + capture: Option<bool>, payment_solution: Option<String>, + commerce_indicator: String, } #[derive(Debug, Serialize)] @@ -102,6 +108,17 @@ pub struct MerchantDefinedInformation { value: String, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformation { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + directory_server_transaction_id: Option<String>, + specification_version: Option<String>, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CaptureOptions { @@ -287,6 +304,28 @@ impl } } +impl + From<( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + )> for OrderInformationWithBill +{ + fn from( + (item, bill_to): ( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + ), + ) -> Self { + Self { + amount_details: Amount { + total_amount: item.amount.to_owned(), + currency: item.router_data.request.currency, + }, + bill_to, + } + } +} + impl From<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -300,11 +339,40 @@ impl ), ) -> Self { Self { - capture: matches!( + capture: Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | None - ), + )), payment_solution: solution.map(String::from), + commerce_indicator: String::from("internet"), + } + } +} + +impl + From<( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &BankOfAmericaConsumerAuthValidateResponse, + )> for ProcessingInformation +{ + fn from( + (item, solution, three_ds_data): ( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &BankOfAmericaConsumerAuthValidateResponse, + ), + ) -> Self { + Self { + capture: Some(matches!( + item.router_data.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + )), + payment_solution: solution.map(String::from), + commerce_indicator: three_ds_data + .indicator + .to_owned() + .unwrap_or(String::from("internet")), } } } @@ -319,6 +387,16 @@ impl From<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } +impl From<&BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for ClientReferenceInformation +{ + fn from(item: &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>) -> Self { + Self { + code: Some(item.router_data.connector_request_reference_id.clone()), + } + } +} + impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> { fn foreign_from(metadata: Value) -> Self { let hashmap: std::collections::BTreeMap<String, Value> = @@ -367,6 +445,83 @@ pub struct Avs { code_raw: String, } +impl + TryFrom<( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + )> for BankOfAmericaPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, ccard): ( + &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + + let three_ds_info: BankOfAmericaThreeDSMetadata = item + .router_data + .request + .connector_meta + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "connector_meta", + })? + .parse_value("BankOfAmericaThreeDSMetadata") + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "Merchant connector account metadata", + })?; + + let processing_information = + ProcessingInformation::from((item, None, &three_ds_info.three_ds_data)); + + let consumer_authentication_information = Some(BankOfAmericaConsumerAuthInformation { + ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator, + cavv: three_ds_info.three_ds_data.cavv, + ucaf_authentication_data: three_ds_info.three_ds_data.ucaf_authentication_data, + xid: three_ds_info.three_ds_data.xid, + directory_server_transaction_id: three_ds_info + .three_ds_data + .directory_server_transaction_id, + specification_version: three_ds_info.three_ds_data.specification_version, + }); + + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information, + merchant_defined_information, + }) + } +} + impl TryFrom<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -410,6 +565,7 @@ impl order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -455,6 +611,7 @@ impl order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -496,6 +653,7 @@ impl order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -552,6 +710,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> order_information, merchant_defined_information, client_reference_information, + consumer_authentication_information: None, }) } } @@ -608,6 +767,64 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaAuthSetupRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, +} + +impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> + for BankOfAmericaAuthSetupRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + Ok(Self { + payment_information, + client_reference_information, + }) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), + ) + .into()) + } + } + } +} + #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BankofamericaPaymentStatus { @@ -669,6 +886,29 @@ impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus { } } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationResponse { + access_token: String, + device_data_collection_url: String, + reference_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthSetupInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum BankOfAmericaAuthSetupResponse { + ClientAuthSetupInfo(ClientAuthSetupInfoResponse), + ErrorInformation(BankOfAmericaErrorInformationResponse), +} + #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum BankOfAmericaPaymentsResponse { @@ -799,6 +1039,494 @@ fn get_payment_response( } } +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BankOfAmericaAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BankOfAmericaAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BankOfAmericaAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self { + status: enums::AttemptStatus::AuthenticationPending, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: Some(services::RedirectForm::CybersourceAuthSetup { + access_token: info_response + .consumer_authentication_information + .access_token, + ddc_url: info_response + .consumer_authentication_information + .device_data_collection_url, + reference_id: info_response + .consumer_authentication_information + .reference_id, + }), + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ), + incremental_authorization_allowed: None, + }), + ..item.data + }), + BankOfAmericaAuthSetupResponse::ErrorInformation(error_response) => { + let error_reason = error_response + .error_information + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason; + Ok(Self { + response: Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }), + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationRequest { + return_url: String, + reference_id: String, +} +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaAuthEnrollmentRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationRequest, + order_information: OrderInformationWithBill, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub struct BankOfAmericaRedirectionAuthResponse { + pub transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationValidateRequest { + authentication_transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaAuthValidateRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationValidateRequest, + order_information: OrderInformation, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum BankOfAmericaPreProcessingRequest { + AuthEnrollment(BankOfAmericaAuthEnrollmentRequest), + AuthValidate(BankOfAmericaAuthValidateRequest), +} + +impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsPreProcessingRouterData>> + for BankOfAmericaPreProcessingRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BankOfAmericaRouterData<&types::PaymentsPreProcessingRouterData>, + ) -> Result<Self, Self::Error> { + let client_reference_information = ClientReferenceInformation { + code: Some(item.router_data.connector_request_reference_id.clone()), + }; + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "payment_method_data", + }, + )?; + let payment_information = match payment_method_data { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + Ok(PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + })) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), + )) + } + }?; + + let redirect_response = item.router_data.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + + let amount_details = Amount { + total_amount: item.amount.clone(), + currency: item.router_data.request.currency.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "currency", + }, + )?, + }; + + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => { + let reference_id = param + .clone() + .peek() + .split_once('=') + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.params.reference_id", + })? + .1 + .to_string(); + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill { + amount_details, + bill_to, + }; + Ok(Self::AuthEnrollment(BankOfAmericaAuthEnrollmentRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + BankOfAmericaConsumerAuthInformationRequest { + return_url: item.router_data.request.get_complete_authorize_url()?, + reference_id, + }, + order_information, + })) + } + Some(_) | None => { + let redirect_payload: BankOfAmericaRedirectionAuthResponse = redirect_response + .payload + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.payload", + })? + .peek() + .clone() + .parse_value("BankOfAmericaRedirectionAuthResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let order_information = OrderInformation { amount_details }; + Ok(Self::AuthValidate(BankOfAmericaAuthValidateRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + BankOfAmericaConsumerAuthInformationValidateRequest { + authentication_transaction_id: redirect_payload.transaction_id, + }, + order_information, + })) + } + } + } +} + +impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for BankOfAmericaPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &BankOfAmericaRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_data", + }, + )?; + match payment_method_data { + payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("BankOfAmerica"), + ) + .into()) + } + } + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum BankOfAmericaAuthEnrollmentStatus { + PendingAuthentication, + AuthenticationSuccessful, + AuthenticationFailed, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthValidateResponse { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + specification_version: Option<String>, + directory_server_transaction_id: Option<String>, + indicator: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct BankOfAmericaThreeDSMetadata { + three_ds_data: BankOfAmericaConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BankOfAmericaConsumerAuthInformationEnrollmentResponse { + access_token: Option<String>, + step_up_url: Option<String>, + //Added to segregate the three_ds_data in a separate struct + #[serde(flatten)] + validate_response: BankOfAmericaConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthCheckInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: BankOfAmericaConsumerAuthInformationEnrollmentResponse, + status: BankOfAmericaAuthEnrollmentStatus, + error_information: Option<BankOfAmericaErrorInformation>, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum BankOfAmericaPreProcessingResponse { + ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), + ErrorInformation(BankOfAmericaErrorInformationResponse), +} + +impl From<BankOfAmericaAuthEnrollmentStatus> for enums::AttemptStatus { + fn from(item: BankOfAmericaAuthEnrollmentStatus) -> Self { + match item { + BankOfAmericaAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending, + BankOfAmericaAuthEnrollmentStatus::AuthenticationSuccessful => { + Self::AuthenticationSuccessful + } + BankOfAmericaAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed, + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BankOfAmericaPreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BankOfAmericaPreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BankOfAmericaPreProcessingResponse::ClientAuthCheckInfo(info_response) => { + let status = enums::AttemptStatus::from(info_response.status); + let risk_info: Option<ClientRiskInformation> = None; + if utils::is_payment_failure(status) { + let response = Err(types::ErrorResponse::from(( + &info_response.error_information, + &risk_info, + item.http_code, + info_response.id.clone(), + ))); + + Ok(Self { + status, + response, + ..item.data + }) + } else { + let connector_response_reference_id = Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ); + + let redirection_data = match ( + info_response + .consumer_authentication_information + .access_token, + info_response + .consumer_authentication_information + .step_up_url, + ) { + (Some(access_token), Some(step_up_url)) => { + Some(services::RedirectForm::CybersourceConsumerAuth { + access_token, + step_up_url, + }) + } + _ => None, + }; + let three_ds_data = serde_json::to_value( + info_response + .consumer_authentication_information + .validate_response, + ) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data, + mandate_reference: None, + connector_metadata: Some( + serde_json::json!({"three_ds_data":three_ds_data}), + ), + network_txn_id: None, + connector_response_reference_id, + incremental_authorization_allowed: None, + }), + ..item.data + }) + } + } + BankOfAmericaPreProcessingResponse::ErrorInformation(ref error_response) => { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + Ok(Self { + response, + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + BankOfAmericaPaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + BankOfAmericaPaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { + let status = enums::AttemptStatus::foreign_from(( + info_response.status.clone(), + item.data.request.is_auto_capture()?, + )); + let response = get_payment_response((&info_response, status, item.http_code)); + Ok(Self { + status, + response, + ..item.data + }) + } + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))) + } + } + } +} + impl<F> TryFrom< types::ResponseRouterData< diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 69159c10c8a..b300e97b44a 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -874,6 +874,33 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } + + fn get_5xx_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: cybersource::CybersourceServerErrorResponse = res + .response + .parse_struct("CybersourceServerErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let attempt_status = match response.reason { + Some(reason) => match reason { + transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure), + transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None, + }, + None => None, + }; + Ok(types::ErrorResponse { + status_code: res.status_code, + reason: response.status.clone(), + code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: response + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + attempt_status, + connector_transaction_id: None, + }) + } } impl diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 21cdec92ccb..49a9bcf6664 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1489,7 +1489,8 @@ where router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) - } else if connector.connector_name == router_types::Connector::Cybersource + } else if (connector.connector_name == router_types::Connector::Cybersource + || connector.connector_name == router_types::Connector::Bankofamerica) && is_operation_complete_authorize(&operation) && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs { diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 6dd692f1525..c9f9d6d87f5 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -147,7 +147,6 @@ impl<const T: u8> default_imp_for_complete_authorize!( connector::Aci, connector::Adyen, - connector::Bankofamerica, connector::Bitpay, connector::Boku, connector::Cashtocode, @@ -863,7 +862,6 @@ default_imp_for_pre_processing_steps!( connector::Airwallex, connector::Authorizedotnet, connector::Bambora, - connector::Bankofamerica, connector::Bitpay, connector::Bluesnap, connector::Boku,
2024-01-12T11:58:44Z
## Description <!-- Describe your changes in detail --> Implement 3DS flow for cards ``` Legend: UB: User Browser M: Merchant HS: Hyperswitch CS: Bankofamerica/Cybersource Connector ``` ![3DS FLOW DIAGRAM](https://github.com/juspay/hyperswitch/assets/41580413/9f2e0e71-65df-4310-84cf-1419090a680f) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3342 # ### QA Testing ![Screenshot 2024-01-12 at 5 35 04 PM](https://github.com/juspay/hyperswitch/assets/41580413/bdab526f-736b-44c1-8904-3ae51e9781f6) ![Screenshot 2024-01-12 at 5 33 54 PM](https://github.com/juspay/hyperswitch/assets/41580413/55ca3a43-b8de-43f8-b463-3555a8e79e21) ![Screenshot 2024-01-12 at 5 33 10 PM](https://github.com/juspay/hyperswitch/assets/41580413/6a9d3d59-1a7d-411d-b5e3-61f59376e9c8) ![Screenshot 2024-01-12 at 5 33 28 PM](https://github.com/juspay/hyperswitch/assets/41580413/3ea39f9f-2ea1-4d25-a85e-fcb9b9522e31) - Test Non-3DS flows to confirm they are not affected - Test 3DS transactions All the possible 3DS test cases and test cards are available here: https://developer.cybersource.com/content/dam/docs/cybs/en-us/payer-authentication/developer/all/rest/payer-auth.pdf 3DS Payment Curl: `curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 1404, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "340000000001098", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph", "card_cvc": "123" } }, "billing": { "address": { "line1": "sdv", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "46282", "country": "US", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "count_tickets": "1", "transaction_number": 2233 }, "business_label": "food", "business_country": "US" }'`
8678f8d1448b5ce430931bfbbc269ef979d9eea7
### QA Testing ![Screenshot 2024-01-12 at 5 35 04 PM](https://github.com/juspay/hyperswitch/assets/41580413/bdab526f-736b-44c1-8904-3ae51e9781f6) ![Screenshot 2024-01-12 at 5 33 54 PM](https://github.com/juspay/hyperswitch/assets/41580413/55ca3a43-b8de-43f8-b463-3555a8e79e21) ![Screenshot 2024-01-12 at 5 33 10 PM](https://github.com/juspay/hyperswitch/assets/41580413/6a9d3d59-1a7d-411d-b5e3-61f59376e9c8) ![Screenshot 2024-01-12 at 5 33 28 PM](https://github.com/juspay/hyperswitch/assets/41580413/3ea39f9f-2ea1-4d25-a85e-fcb9b9522e31) - Test Non-3DS flows to confirm they are not affected - Test 3DS transactions All the possible 3DS test cases and test cards are available here: https://developer.cybersource.com/content/dam/docs/cybs/en-us/payer-authentication/developer/all/rest/payer-auth.pdf 3DS Payment Curl: `curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 1404, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "340000000001098", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph", "card_cvc": "123" } }, "billing": { "address": { "line1": "sdv", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "46282", "country": "US", "first_name": "joseph", "last_name": "ewcjwd" }, "phone": { "number": "8056594427", "country_code": "+97" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "count_tickets": "1", "transaction_number": 2233 }, "business_label": "food", "business_country": "US" }'`
[ "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/router/src/connector/bankofamerica.rs", "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cybersource.rs", "crates/router/src/core/payments.rs", "crates/router/src/cor...
juspay/hyperswitch
juspay__hyperswitch-3340
Bug: Rename `s3` feature flag to `aws_s3` Rename `s3` feature flag to `aws_s3`. This change is required so that current storage scheme becomes distinguishable, especially if in future new storage implementations like a AWS S3 alternative is integrated.
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 8897fdac2c2..88272033fb0 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,12 +10,12 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] -s3 = ["dep:aws-sdk-s3", "dep:aws-config"] +aws_s3 = ["dep:aws-sdk-s3", "dep:aws-config"] kms = ["external_services/kms", "dep:aws-config"] email = ["external_services/email", "dep:aws-config", "olap"] frm = [] stripe = ["dep:serde_qs"] -release = ["kms", "stripe", "s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] +release = ["kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3d93c2f188b..b674c503542 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -88,7 +88,7 @@ pub struct Settings { pub api_keys: ApiKeys, #[cfg(feature = "kms")] pub kms: kms::KmsConfig, - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] pub file_upload_config: FileUploadConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, @@ -716,7 +716,7 @@ pub struct ApiKeys { pub expiry_reminder_days: Vec<u8>, } -#[cfg(feature = "s3")] +#[cfg(feature = "aws_s3")] #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct FileUploadConfig { @@ -848,7 +848,7 @@ impl Settings { self.kms .validate() .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?; - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] self.file_upload_config.validate()?; self.lock_settings.validate()?; self.events.validate()?; diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 569262d0d21..0b286ece843 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -127,7 +127,7 @@ impl super::settings::DrainerSettings { } } -#[cfg(feature = "s3")] +#[cfg(feature = "aws_s3")] impl super::settings::FileUploadConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs index 13c4d3dfdf3..f3e56489806 100644 --- a/crates/router/src/core/files.rs +++ b/crates/router/src/core/files.rs @@ -1,8 +1,8 @@ pub mod helpers; -#[cfg(feature = "s3")] +#[cfg(feature = "aws_s3")] pub mod s3_utils; -#[cfg(not(feature = "s3"))] +#[cfg(not(feature = "aws_s3"))] pub mod fs_utils; use api_models::files; @@ -29,9 +29,9 @@ pub async fn files_create_core( ) .await?; let file_id = common_utils::generate_id(consts::ID_LENGTH, "file"); - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] let file_key = format!("{}/{}", merchant_account.merchant_id, file_id); - #[cfg(not(feature = "s3"))] + #[cfg(not(feature = "aws_s3"))] let file_key = format!("{}_{}", merchant_account.merchant_id, file_id); let file_new = diesel_models::file::FileMetadataNew { file_id: file_id.clone(), diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs index 818067207f4..9205d42aeee 100644 --- a/crates/router/src/core/files/helpers.rs +++ b/crates/router/src/core/files/helpers.rs @@ -31,33 +31,33 @@ pub async fn get_file_purpose(field: &mut Field) -> Option<api::FilePurpose> { } pub async fn upload_file( - #[cfg(feature = "s3")] state: &AppState, + #[cfg(feature = "aws_s3")] state: &AppState, file_key: String, file: Vec<u8>, ) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] return files::s3_utils::upload_file_to_s3(state, file_key, file).await; - #[cfg(not(feature = "s3"))] + #[cfg(not(feature = "aws_s3"))] return files::fs_utils::save_file_to_fs(file_key, file); } pub async fn delete_file( - #[cfg(feature = "s3")] state: &AppState, + #[cfg(feature = "aws_s3")] state: &AppState, file_key: String, ) -> CustomResult<(), errors::ApiErrorResponse> { - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] return files::s3_utils::delete_file_from_s3(state, file_key).await; - #[cfg(not(feature = "s3"))] + #[cfg(not(feature = "aws_s3"))] return files::fs_utils::delete_file_from_fs(file_key); } pub async fn retrieve_file( - #[cfg(feature = "s3")] state: &AppState, + #[cfg(feature = "aws_s3")] state: &AppState, file_key: String, ) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> { - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] return files::s3_utils::retrieve_file_from_s3(state, file_key).await; - #[cfg(not(feature = "s3"))] + #[cfg(not(feature = "aws_s3"))] return files::fs_utils::retrieve_file_from_fs(file_key); } @@ -134,7 +134,7 @@ pub async fn delete_file_using_file_id( match provider { diesel_models::enums::FileUploadProvider::Router => { delete_file( - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] state, provider_file_id, ) @@ -235,7 +235,7 @@ pub async fn retrieve_file_and_provider_file_id_from_file_id( diesel_models::enums::FileUploadProvider::Router => Ok(( Some( retrieve_file( - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] state, provider_file_id.clone(), ) @@ -365,7 +365,7 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id( )) } else { upload_file( - #[cfg(feature = "s3")] + #[cfg(feature = "aws_s3")] state, file_key.clone(), create_file_request.file.clone(),
2024-01-12T11:03:29Z
## Description <!-- Describe your changes in detail --> This PR renames s3 feature flag to aws_s3 so that current storage scheme is distinguishable, especially if in future new storage implementations like a AWS S3 alternative is integrated. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
eb2a61d8597995838f21b8233653c691118b2191
Just a rename of feature flag, so basic sanity testing should work
[ "crates/router/Cargo.toml", "crates/router/src/configs/settings.rs", "crates/router/src/configs/validations.rs", "crates/router/src/core/files.rs", "crates/router/src/core/files/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3339
Bug: Event Viewer - Add payment_id to PaymentsList API call `PaymentsList` Api call currently does not extract the payment id from payload. Since this API is associated with a payment, we need to add a `payment_id` field to this API call as well
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 26a9d222d6b..3eb19fcc3d8 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -37,7 +37,6 @@ impl ApiEventMetric for TimeRange {} impl_misc_api_event_type!( PaymentMethodId, PaymentsSessionResponse, - PaymentMethodListResponse, PaymentMethodCreate, PaymentLinkInitiateRequest, RetrievePaymentLinkResponse, diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index f718dc1ca4d..32d3dc30bd8 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -3,7 +3,7 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::{ payment_methods::{ CustomerPaymentMethodsListResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest, - PaymentMethodResponse, PaymentMethodUpdate, + PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints, PaymentListFilters, @@ -119,6 +119,8 @@ impl ApiEventMetric for PaymentMethodListRequest { } } +impl ApiEventMetric for PaymentMethodListResponse {} + impl ApiEventMetric for PaymentListFilterConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI)
2024-01-12T08:22:57Z
## Description <!-- Describe your changes in detail --> - Add payment_id field in payment methods list ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
d533c98b5107fb6876c11b183eb9bc382a77a2f1
1. create a payment with confirm false 2. call `List payment methods for a Merchant` API via postman
[ "crates/api_models/src/events.rs", "crates/api_models/src/events/payment.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3441
Bug: [DOCS] Add Api-Refrence for Blocklist This PR adds the api contracts(utoipa) for all blocklist apis.
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs index fc838eed5ce..888b9106ccc 100644 --- a/crates/api_models/src/blocklist.rs +++ b/crates/api_models/src/blocklist.rs @@ -1,7 +1,8 @@ use common_enums::enums; use common_utils::events::ApiEventMetric; +use utoipa::ToSchema; -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "data")] pub enum BlocklistRequest { CardBin(String), @@ -12,9 +13,10 @@ pub enum BlocklistRequest { pub type AddToBlocklistRequest = BlocklistRequest; pub type DeleteFromBlocklistRequest = BlocklistRequest; -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BlocklistResponse { pub fingerprint_id: String, + #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, @@ -23,8 +25,9 @@ pub struct BlocklistResponse { pub type AddToBlocklistResponse = BlocklistResponse; pub type DeleteFromBlocklistResponse = BlocklistResponse; -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ListBlocklistQuery { + #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(default = "default_list_limit")] pub limit: u16, diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rs index c263bef63c5..93361552de7 100644 --- a/crates/router/src/db/blocklist.rs +++ b/crates/router/src/db/blocklist.rs @@ -163,41 +163,49 @@ impl BlocklistInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, - _pm_blocklist: storage::BlocklistNew, + pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store.insert_blocklist_entry(pm_blocklist).await } async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, - _merchant_id: &str, - _fingerprint_id: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) + .await } async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, - _merchant_id: &str, - _fingerprint_id: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) + .await } async fn list_blocklist_entries_by_merchant_id_data_kind( &self, - _merchant_id: &str, - _data_kind: common_enums::BlocklistDataKind, - _limit: i64, - _offset: i64, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, + limit: i64, + offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .list_blocklist_entries_by_merchant_id_data_kind(merchant_id, data_kind, limit, offset) + .await } async fn list_blocklist_entries_by_merchant_id( &self, - _merchant_id: &str, + merchant_id: &str, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .list_blocklist_entries_by_merchant_id(merchant_id) + .await } } diff --git a/crates/router/src/db/blocklist_fingerprint.rs b/crates/router/src/db/blocklist_fingerprint.rs index 9da7c7d8fb2..d9107d3d1c1 100644 --- a/crates/router/src/db/blocklist_fingerprint.rs +++ b/crates/router/src/db/blocklist_fingerprint.rs @@ -80,16 +80,20 @@ impl BlocklistFingerprintInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_fingerprint_entry( &self, - _pm_fingerprint_new: storage::BlocklistFingerprintNew, + pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .insert_blocklist_fingerprint_entry(pm_fingerprint_new) + .await } async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, - _merchant_id: &str, - _fingerprint_id: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .find_blocklist_fingerprint_by_merchant_id_fingerprint_id(merchant_id, fingerprint) + .await } } diff --git a/crates/router/src/db/blocklist_lookup.rs b/crates/router/src/db/blocklist_lookup.rs index 0dfd81c8b8a..f5fb4ea9ed8 100644 --- a/crates/router/src/db/blocklist_lookup.rs +++ b/crates/router/src/db/blocklist_lookup.rs @@ -102,24 +102,30 @@ impl BlocklistLookupInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, - _blocklist_lookup_entry: storage::BlocklistLookupNew, + blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .insert_blocklist_lookup_entry(blocklist_lookup_entry) + .await } async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, - _merchant_id: &str, - _fingerprint: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .find_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) + .await } async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, - _merchant_id: &str, - _fingerprint: &str, + merchant_id: &str, + fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { - Err(errors::StorageError::KafkaError)? + self.diesel_store + .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) + .await } } diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 79b38e03f31..174926c7d36 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -119,6 +119,9 @@ Never share your secret api keys. Keep them guarded and secure. crate::routes::gsm::get_gsm_rule, crate::routes::gsm::update_gsm_rule, crate::routes::gsm::delete_gsm_rule, + crate::routes::blocklist::add_entry_to_blocklist, + crate::routes::blocklist::list_blocked_payment_methods, + crate::routes::blocklist::remove_entry_from_blocklist ), components(schemas( crate::types::api::refunds::RefundRequest, @@ -370,7 +373,11 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentLinkResponse, api_models::payments::RetrievePaymentLinkResponse, api_models::payments::PaymentLinkInitiateRequest, - api_models::payments::PaymentLinkStatus + api_models::payments::PaymentLinkStatus, + api_models::blocklist::BlocklistRequest, + api_models::blocklist::BlocklistResponse, + api_models::blocklist::ListBlocklistQuery, + common_enums::enums::BlocklistDataKind )), modifiers(&SecurityAddon) )] diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs index 7c268dddeec..9c93f49ab83 100644 --- a/crates/router/src/routes/blocklist.rs +++ b/crates/router/src/routes/blocklist.rs @@ -8,6 +8,18 @@ use crate::{ services::{api, authentication as auth, authorization::permissions::Permission}, }; +#[utoipa::path( + post, + path = "/blocklist", + request_body = BlocklistRequest, + responses( + (status = 200, description = "Fingerprint Blocked", body = BlocklistResponse), + (status = 400, description = "Invalid Data") + ), + tag = "Blocklist", + operation_id = "Block a Fingerprint", + security(("api_key" = [])) +)] pub async fn add_entry_to_blocklist( state: web::Data<AppState>, req: HttpRequest, @@ -32,6 +44,18 @@ pub async fn add_entry_to_blocklist( .await } +#[utoipa::path( + delete, + path = "/blocklist", + request_body = BlocklistRequest, + responses( + (status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse), + (status = 400, description = "Invalid Data") + ), + tag = "Blocklist", + operation_id = "Unblock a Fingerprint", + security(("api_key" = [])) +)] pub async fn remove_entry_from_blocklist( state: web::Data<AppState>, req: HttpRequest, @@ -56,6 +80,20 @@ pub async fn remove_entry_from_blocklist( .await } +#[utoipa::path( + get, + path = "/blocklist", + params ( + ("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"), + ), + responses( + (status = 200, description = "Blocked Fingerprints", body = BlocklistResponse), + (status = 400, description = "Invalid Data") + ), + tag = "Blocklist", + operation_id = "List Blocked fingerprints of a particular kind", + security(("api_key" = [])) +)] pub async fn list_blocked_payment_methods( state: web::Data<AppState>, req: HttpRequest, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 3e582cfed52..c50f687a181 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -382,6 +382,117 @@ ] } }, + "/blocklist": { + "get": { + "tags": [ + "Blocklist" + ], + "operationId": "List Blocked fingerprints of a particular kind", + "parameters": [ + { + "name": "data_kind", + "in": "query", + "description": "Kind of the fingerprint list requested", + "required": true, + "schema": { + "$ref": "#/components/schemas/BlocklistDataKind" + } + } + ], + "responses": { + "200": { + "description": "Blocked Fingerprints", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "post": { + "tags": [ + "Blocklist" + ], + "operationId": "Block a Fingerprint", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Fingerprint Blocked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "delete": { + "tags": [ + "Blocklist" + ], + "operationId": "Unblock a Fingerprint", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Fingerprint Unblocked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BlocklistResponse" + } + } + } + }, + "400": { + "description": "Invalid Data" + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, "/customers": { "post": { "tags": [ @@ -4035,6 +4146,95 @@ } ] }, + "BlocklistDataKind": { + "type": "string", + "enum": [ + "payment_method", + "card_bin", + "extended_card_bin" + ] + }, + "BlocklistRequest": { + "oneOf": [ + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "card_bin" + ] + }, + "data": { + "type": "string" + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "fingerprint" + ] + }, + "data": { + "type": "string" + } + } + }, + { + "type": "object", + "required": [ + "type", + "data" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "extended_card_bin" + ] + }, + "data": { + "type": "string" + } + } + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "BlocklistResponse": { + "type": "object", + "required": [ + "fingerprint_id", + "data_kind", + "created_at" + ], + "properties": { + "fingerprint_id": { + "type": "string" + }, + "data_kind": { + "$ref": "#/components/schemas/BlocklistDataKind" + }, + "created_at": { + "type": "string", + "format": "date-time" + } + } + }, "BoletoVoucherData": { "type": "object", "properties": { @@ -6576,6 +6776,27 @@ } } }, + "ListBlocklistQuery": { + "type": "object", + "required": [ + "data_kind" + ], + "properties": { + "data_kind": { + "$ref": "#/components/schemas/BlocklistDataKind" + }, + "limit": { + "type": "integer", + "format": "int32", + "minimum": 0 + }, + "offset": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } + }, "MandateAmountData": { "type": "object", "required": [
2024-01-11T19:39:29Z
## Description <!-- Describe your changes in detail --> This PR adds the api contracts(utoipa) for blocklist apis. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
57f2cff75e58b0a7811492a1fdb636f59dcefbd0
The test cases can be found out here in this [PR](https://github.com/juspay/hyperswitch/pull/3056).
[ "crates/api_models/src/blocklist.rs", "crates/router/src/db/blocklist.rs", "crates/router/src/db/blocklist_fingerprint.rs", "crates/router/src/db/blocklist_lookup.rs", "crates/router/src/openapi.rs", "crates/router/src/routes/blocklist.rs", "openapi/openapi_spec.json" ]
juspay/hyperswitch
juspay__hyperswitch-3327
Bug: feat: Add user flow for non-email usecase If a user (merchant) does not have email service enabled, then the current invite user flow does not work. ## Feature Requirement For a merchant with no email service enabled (feature flag), have a add user flow. In this flow, the merchant is asked for a email id and password. A user will be created with this new email ID and password and he will be able to log in.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 07909a35782..f5af31c8e7f 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -86,6 +86,7 @@ pub struct InviteUserRequest { #[derive(Debug, serde::Serialize)] pub struct InviteUserResponse { pub is_email_sent: bool, + pub password: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 532f8208ecf..b1a582cedec 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1,7 +1,5 @@ use api_models::user as user_api; -#[cfg(feature = "email")] -use diesel_models::user_role::UserRoleNew; -use diesel_models::{enums::UserStatus, user as storage_user}; +use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew}; #[cfg(feature = "email")] use error_stack::IntoReport; use error_stack::ResultExt; @@ -342,7 +340,6 @@ pub async fn reset_password( Ok(ApplicationResponse::StatusOk) } -#[cfg(feature = "email")] pub async fn invite_user( state: AppState, request: user_api::InviteUserRequest, @@ -395,6 +392,7 @@ pub async fn invite_user( Ok(ApplicationResponse::Json(user_api::InviteUserResponse { is_email_sent: false, + password: None, })) } else if invitee_user .as_ref() @@ -432,25 +430,37 @@ pub async fn invite_user( } })?; - let email_contents = email_types::InviteUser { - recipient_email: invitee_email, - user_name: domain::UserName::new(new_user.get_name())?, - settings: state.conf.clone(), - subject: "You have been invited to join Hyperswitch Community!", - }; - - let send_email_result = state - .email_client - .compose_and_send_email( - Box::new(email_contents), - state.conf.proxy.https_url.as_ref(), - ) - .await; - - logger::info!(?send_email_result); + let is_email_sent; + #[cfg(feature = "email")] + { + let email_contents = email_types::InviteUser { + recipient_email: invitee_email, + user_name: domain::UserName::new(new_user.get_name())?, + settings: state.conf.clone(), + subject: "You have been invited to join Hyperswitch Community!", + }; + let send_email_result = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await; + logger::info!(?send_email_result); + is_email_sent = send_email_result.is_ok(); + } + #[cfg(not(feature = "email"))] + { + is_email_sent = false; + } Ok(ApplicationResponse::Json(user_api::InviteUserResponse { - is_email_sent: send_email_result.is_ok(), + is_email_sent, + password: if cfg!(not(feature = "email")) { + Some(new_user.get_password().get_secret()) + } else { + None + }, })) } else { Err(UserErrors::InternalServerError.into()) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6625a206be2..015e3305de1 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -879,6 +879,7 @@ impl User { .service(web::resource("/user/update_role").route(web::post().to(update_user_role))) .service(web::resource("/role/list").route(web::get().to(list_roles))) .service(web::resource("/role/{role_id}").route(web::get().to(get_role))) + .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service( web::resource("/data") .route(web::get().to(get_multiple_dashboard_metadata)) @@ -901,7 +902,6 @@ impl User { ) .service(web::resource("/forgot_password").route(web::post().to(forgot_password))) .service(web::resource("/reset_password").route(web::post().to(reset_password))) - .service(web::resource("/user/invite").route(web::post().to(invite_user))) .service( web::resource("/signup_with_merchant_id") .route(web::post().to(user_signup_with_merchant_id)), diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 7f0f0db3b69..a77b82c550e 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -333,7 +333,6 @@ pub async fn reset_password( .await } -#[cfg(feature = "email")] pub async fn invite_user( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8f204814ec4..d271ed5e29d 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -489,6 +489,10 @@ impl NewUser { self.new_merchant.clone() } + pub fn get_password(&self) -> UserPassword { + self.password.clone() + } + pub async fn insert_user_in_db( &self, db: &dyn StorageInterface, @@ -683,8 +687,7 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.0.email.clone().try_into()?; let name = UserName::new(value.0.name.clone())?; - let password = password::generate_password_hash(uuid::Uuid::new_v4().to_string().into())?; - let password = UserPassword::new(password)?; + let password = UserPassword::new(uuid::Uuid::new_v4().to_string().into())?; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self {
2024-01-11T10:13:42Z
## Description Enabled invite api to work without "email" feature flag <!-- Describe your changes in detail --> ## Motivation and Context allows user to use user management without email feature flag. <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
9eaebe8db3d83105ef1e8fc784241e1fb795dd22
``` curl --location --request POST '<URL>/user/user/invite' \ --header 'Authorization: Bearer <JWT>' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "name": "name", "role_id": "valid_role_id" }' ``` Expected Response: with email flag ``` { "is_email_sent": true, "password": null } ``` without email flag ``` { "is_email_sent": false, "password": "some_password" } ```
[ "crates/api_models/src/user.rs", "crates/router/src/core/user.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/user.rs", "crates/router/src/types/domain/user.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3514
Bug: [FEATURE] send metadata field in authentication request for nmi, noon and cryptopay ### Feature Description Send metadata in the authorize request for noon, nmi and cryptopay. ### Possible Implementation metadata field is being sent in routerData.request for Authorize request. This needs to be mapped to connector request body. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 0540d470a94..ef1812acf11 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -642,7 +642,7 @@ pub struct PaymentMethodListResponse { pub redirect_url: Option<String>, /// currency of the Payment to be done - #[schema(example = "USD")] + #[schema(example = "USD", value_type = Currency)] pub currency: Option<api_enums::Currency>, /// Information about the payment method diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 4102945b201..fb806fda68f 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -1,3 +1,4 @@ +use common_utils::pii; use masking::Secret; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -47,6 +48,7 @@ pub struct CryptopayPaymentsRequest { pay_currency: String, success_redirect_url: Option<String>, unsuccess_redirect_url: Option<String>, + metadata: Option<pii::SecretSerdeValue>, custom_id: String, } @@ -66,6 +68,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> pay_currency, success_redirect_url: item.router_data.request.router_return_url.clone(), unsuccess_redirect_url: item.router_data.request.router_return_url.clone(), + metadata: item.router_data.request.metadata.clone(), custom_id: item.router_data.connector_request_reference_id.clone(), }) } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 5b486aae600..395781cc516 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -1,8 +1,8 @@ use api_models::webhooks; use cards::CardNumber; -use common_utils::{errors::CustomResult, ext_traits::XmlExt}; +use common_utils::{errors::CustomResult, ext_traits::XmlExt, pii}; use error_stack::{IntoReport, Report, ResultExt}; -use masking::{ExposeInterface, Secret}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -403,9 +403,35 @@ pub struct NmiPaymentsRequest { currency: enums::Currency, #[serde(flatten)] payment_method: PaymentMethod, + #[serde(flatten)] + merchant_defined_field: Option<NmiMerchantDefinedField>, orderid: String, } +#[derive(Debug, Serialize)] +pub struct NmiMerchantDefinedField { + #[serde(flatten)] + inner: std::collections::BTreeMap<String, Secret<String>>, +} + +impl NmiMerchantDefinedField { + pub fn new(metadata: &pii::SecretSerdeValue) -> Self { + let metadata_as_string = metadata.peek().to_string(); + let hash_map: std::collections::BTreeMap<String, serde_json::Value> = + serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new()); + let inner = hash_map + .into_iter() + .enumerate() + .map(|(index, (hs_key, hs_value))| { + let nmi_key = format!("merchant_defined_field_{}", index + 1); + let nmi_value = format!("{hs_key}={hs_value}"); + (nmi_key, Secret::new(nmi_value)) + }) + .collect(); + Self { inner } + } +} + #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentMethod { @@ -451,6 +477,12 @@ impl TryFrom<&NmiRouterData<&types::PaymentsAuthorizeRouterData>> for NmiPayment amount, currency: item.router_data.request.currency, payment_method, + merchant_defined_field: item + .router_data + .request + .metadata + .as_ref() + .map(NmiMerchantDefinedField::new), orderid: item.router_data.connector_request_reference_id.clone(), }) } @@ -564,6 +596,7 @@ impl TryFrom<&types::SetupMandateRouterData> for NmiPaymentsRequest { amount: 0.0, currency: item.request.currency, payment_method, + merchant_defined_field: None, orderid: item.connector_request_reference_id.clone(), }) } diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index 6c98a307637..6e1959b46d0 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -5,8 +5,9 @@ use std::fmt::Debug; use base64::Engine; use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; use diesel_models::enums; -use error_stack::{IntoReport, ResultExt}; +use error_stack::{IntoReport, Report, ResultExt}; use masking::PeekInterface; +use router_env::logger; use transformers as noon; use crate::{ @@ -28,7 +29,7 @@ use crate::{ api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, - utils::BytesExt, + utils::{self, BytesExt}, }; #[derive(Debug, Clone)] @@ -127,19 +128,23 @@ impl ConnectorCommon for Noon { &self, res: Response, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: noon::NoonErrorResponse = res - .response - .parse_struct("NoonErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - Ok(ErrorResponse { - status_code: res.status_code, - code: response.result_code.to_string(), - message: response.class_description, - reason: Some(response.message), - attempt_status: None, - connector_transaction_id: None, - }) + let response: Result<noon::NoonErrorResponse, Report<common_utils::errors::ParsingError>> = + res.response.parse_struct("NoonErrorResponse"); + + match response { + Ok(noon_error_response) => Ok(ErrorResponse { + status_code: res.status_code, + code: consts::NO_ERROR_CODE.to_string(), + message: noon_error_response.class_description, + reason: Some(noon_error_response.message), + attempt_status: None, + connector_transaction_id: None, + }), + Err(error_message) => { + logger::error!(deserialization_error =? error_message); + utils::handle_json_response_deserialization_failure(res, "noon".to_owned()) + } + } } } diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 8bb3a96a3ca..9a6490c5756 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -1,6 +1,6 @@ use common_utils::pii; use error_stack::ResultExt; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ @@ -67,9 +67,46 @@ pub struct NoonOrder { reference: String, //Short description of the order. name: String, + nvp: Option<NoonOrderNvp>, ip_address: Option<Secret<String, pii::IpAddress>>, } +#[derive(Debug, Serialize)] +pub struct NoonOrderNvp { + #[serde(flatten)] + inner: std::collections::BTreeMap<String, Secret<String>>, +} + +fn get_value_as_string(value: &serde_json::Value) -> String { + match value { + serde_json::Value::String(string) => string.to_owned(), + serde_json::Value::Null + | serde_json::Value::Bool(_) + | serde_json::Value::Number(_) + | serde_json::Value::Array(_) + | serde_json::Value::Object(_) => value.to_string(), + } +} + +impl NoonOrderNvp { + pub fn new(metadata: &pii::SecretSerdeValue) -> Self { + let metadata_as_string = metadata.peek().to_string(); + let hash_map: std::collections::BTreeMap<String, serde_json::Value> = + serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new()); + let inner = hash_map + .into_iter() + .enumerate() + .map(|(index, (hs_key, hs_value))| { + let noon_key = format!("{}", index + 1); + // to_string() function on serde_json::Value returns a string with "" quotes. Noon doesn't allow this. Hence get_value_as_string function + let noon_value = format!("{hs_key}={}", get_value_as_string(&hs_value)); + (noon_key, Secret::new(noon_value)) + }) + .collect(); + Self { inner } + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "UPPERCASE")] pub enum NoonPaymentActions { @@ -365,6 +402,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { category, reference: item.connector_request_reference_id.clone(), name, + nvp: item.request.metadata.as_ref().map(NoonOrderNvp::new), ip_address, }; let payment_action = if item.request.is_auto_capture()? { diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 98cfaecf6b8..9992360723e 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -11637,6 +11637,7 @@ "PaymentMethodListResponse": { "type": "object", "required": [ + "currency", "payment_methods", "mandate_payment", "show_surcharge_breakup_screen" @@ -11648,6 +11649,9 @@ "example": "https://www.google.com", "nullable": true }, + "currency": { + "$ref": "#/components/schemas/Currency" + }, "payment_methods": { "type": "array", "items": {
2024-01-11T09:59:47Z
## Description <!-- Describe your changes in detail --> Send metadata in the authorize request for noon, nmi and cryptopay. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
a9c0d0c55492c14a4a10283ffd8deae04c8ea853
Manual. 1. CryptoPay (connector force sync response) <img width="1728" alt="Cryptopay log" src="https://github.com/juspay/hyperswitch/assets/61539176/1975c066-bcb1-4ae8-ad91-c200d92d28fa"> 2. NMI (connector force sync response) Authomatic capture (auth+capture) <img width="1728" alt="Screenshot 2024-02-06 at 12 36 19 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/1d512585-1211-4fae-a7ed-d79f4f30f718"> Manual Capture(auth and then capture) <img width="1728" alt="Screenshot 2024-02-06 at 1 16 28 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/6c9c5401-0bad-4b6f-b419-2d2bddf729ab"> 4. Noon (connector dashboard) <img width="1728" alt="Screenshot 2024-01-31 at 8 25 10 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/6b2b759a-b97d-4acf-894b-2b179f7bbbdc">
[ "crates/api_models/src/payment_methods.rs", "crates/router/src/connector/cryptopay/transformers.rs", "crates/router/src/connector/nmi/transformers.rs", "crates/router/src/connector/noon.rs", "crates/router/src/connector/noon/transformers.rs", "openapi/openapi_spec.json" ]
juspay/hyperswitch
juspay__hyperswitch-3320
Bug: audit trail - add connector events ### Connector Events Audit trail Build a connector events audit trail endpoint for fetching all events from `connector_events_audit` table for ops audit trail. ![Image](https://github.com/juspay/hyperswitch/assets/21202349/3ae37c76-117e-46af-8e5c-3c9b74410efa) can refer to the existing API Events audit trail implementation [here](https://github.com/juspay/hyperswitch/blob/main/crates/analytics/src/api_event/events.rs) ``` curl --location 'https://sandbox.hyperswitch.io/analytics/v1/api_event_logs?type=Payment&payment_id=pay_yEsFwSqi6Umv8LVGFFPD' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjBmZDAyNzAtNTE1MS00MWVhLWJiMWItMGY0ZWExZGNmYjQzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjg5OTI0ODQzIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNzA0ODgyODg5LCJvcmdfaWQiOiJvcmdfRk5ZWjhQaE5CQjdtV1hodWxWQW0ifQ.LCgIW8uMGVo2WRFt2irzQ1D8sHuRBSbeRkTGt1qxsXM' ``` The API contract would involve a simple `GET analytics/v1/connector_event_logs` path. with similar response format as above curl request
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index b8fd5e6a35d..f81c29c801c 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -21,6 +21,7 @@ use crate::{ filters::ApiEventFilter, metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, + connector_events::events::ConnectorEventsResult, outgoing_webhook_event::events::OutgoingWebhookLogsResult, sdk_events::events::SdkEventsResult, types::TableEngine, @@ -121,6 +122,7 @@ impl AnalyticsDataSource for ClickhouseClient { } AnalyticsCollection::SdkEvents => TableEngine::BasicTree, AnalyticsCollection::ApiEvents => TableEngine::BasicTree, + AnalyticsCollection::ConnectorEvents => TableEngine::BasicTree, AnalyticsCollection::OutgoingWebhookEvent => TableEngine::BasicTree, } } @@ -147,6 +149,7 @@ impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} +impl super::connector_events::events::ConnectorEventLogAnalytics for ClickhouseClient {} impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics for ClickhouseClient { @@ -188,6 +191,18 @@ impl TryInto<SdkEventsResult> for serde_json::Value { } } +impl TryInto<ConnectorEventsResult> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<ConnectorEventsResult, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse ConnectorEventsResult in clickhouse results", + )) + } +} + impl TryInto<PaymentMetricRow> for serde_json::Value { type Error = Report<ParsingError>; @@ -344,6 +359,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { Self::SdkEvents => Ok("sdk_events_dist".to_string()), Self::ApiEvents => Ok("api_audit_log".to_string()), Self::PaymentIntent => Ok("payment_intents_dist".to_string()), + Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), } } diff --git a/crates/analytics/src/connector_events.rs b/crates/analytics/src/connector_events.rs new file mode 100644 index 00000000000..c7c31306a2c --- /dev/null +++ b/crates/analytics/src/connector_events.rs @@ -0,0 +1,5 @@ +mod core; +pub mod events; +pub trait ConnectorEventAnalytics: events::ConnectorEventLogAnalytics {} + +pub use self::core::connector_events_core; diff --git a/crates/analytics/src/connector_events/core.rs b/crates/analytics/src/connector_events/core.rs new file mode 100644 index 00000000000..15f841af5f8 --- /dev/null +++ b/crates/analytics/src/connector_events/core.rs @@ -0,0 +1,27 @@ +use api_models::analytics::connector_events::ConnectorEventsRequest; +use common_utils::errors::ReportSwitchExt; +use error_stack::{IntoReport, ResultExt}; + +use super::events::{get_connector_events, ConnectorEventsResult}; +use crate::{errors::AnalyticsResult, types::FiltersError, AnalyticsProvider}; + +pub async fn connector_events_core( + pool: &AnalyticsProvider, + req: ConnectorEventsRequest, + merchant_id: String, +) -> AnalyticsResult<Vec<ConnectorEventsResult>> { + let data = match pool { + AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented( + "Connector Events not implemented for SQLX", + )) + .into_report() + .attach_printable("SQL Analytics is not implemented for Connector Events"), + AnalyticsProvider::Clickhouse(ckh_pool) + | AnalyticsProvider::CombinedSqlx(_, ckh_pool) + | AnalyticsProvider::CombinedCkh(_, ckh_pool) => { + get_connector_events(&merchant_id, req, ckh_pool).await + } + } + .switch()?; + Ok(data) +} diff --git a/crates/analytics/src/connector_events/events.rs b/crates/analytics/src/connector_events/events.rs new file mode 100644 index 00000000000..096520777ee --- /dev/null +++ b/crates/analytics/src/connector_events/events.rs @@ -0,0 +1,63 @@ +use api_models::analytics::{ + connector_events::{ConnectorEventsRequest, QueryType}, + Granularity, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; +pub trait ConnectorEventLogAnalytics: LoadRow<ConnectorEventsResult> {} + +pub async fn get_connector_events<T>( + merchant_id: &String, + query_param: ConnectorEventsRequest, + pool: &T, +) -> FiltersResult<Vec<ConnectorEventsResult>> +where + T: AnalyticsDataSource + ConnectorEventLogAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::ConnectorEvents); + query_builder.add_select_column("*").switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + match query_param.query_param { + QueryType::Payment { payment_id } => query_builder + .add_filter_clause("payment_id", payment_id) + .switch()?, + } + //TODO!: update the execute_query function to return reports instead of plain errors... + query_builder + .execute_query::<ConnectorEventsResult, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct ConnectorEventsResult { + pub merchant_id: String, + pub payment_id: String, + pub connector_name: Option<String>, + pub request_id: Option<String>, + pub flow: String, + pub request: String, + pub response: Option<String>, + pub error: Option<String>, + pub status_code: u16, + pub latency: Option<u128>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, + pub method: Option<String>, +} diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 8529807a1a1..501bd58527c 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -7,6 +7,7 @@ mod query; pub mod refunds; pub mod api_event; +pub mod connector_events; pub mod outgoing_webhook_event; pub mod sdk_events; mod sqlx; diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index e32b85a5367..7ab8a2aa4bc 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -429,6 +429,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection { Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiEvents table is not implemented for Sqlx"))?, Self::PaymentIntent => Ok("payment_intent".to_string()), + Self::ConnectorEvents => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("ConnectorEvents table is not implemented for Sqlx"))?, Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?, } diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 8da4655e255..18e9e9f4334 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -26,6 +26,7 @@ pub enum AnalyticsCollection { SdkEvents, ApiEvents, PaymentIntent, + ConnectorEvents, OutgoingWebhookEvent, } diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index e0d3fa671b6..c6ca215f9f7 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -12,6 +12,7 @@ use self::{ pub use crate::payments::TimeRange; pub mod api_event; +pub mod connector_events; pub mod outgoing_webhook_event; pub mod payments; pub mod refunds; diff --git a/crates/api_models/src/analytics/connector_events.rs b/crates/api_models/src/analytics/connector_events.rs new file mode 100644 index 00000000000..b2974b0a339 --- /dev/null +++ b/crates/api_models/src/analytics/connector_events.rs @@ -0,0 +1,11 @@ +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(tag = "type")] +pub enum QueryType { + Payment { payment_id: String }, +} + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct ConnectorEventsRequest { + #[serde(flatten)] + pub query_param: QueryType, +} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 26a9d222d6b..43a72b7e392 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -17,10 +17,12 @@ use common_utils::{ impl_misc_api_event_type, }; +#[allow(unused_imports)] use crate::{ admin::*, analytics::{ - api_event::*, outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, *, + api_event::*, connector_events::ConnectorEventsRequest, + outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, *, }, api_keys::*, cards_info::*, @@ -94,6 +96,7 @@ impl_misc_api_event_type!( GetApiEventMetricRequest, SdkEventsRequest, ReportRequest, + ConnectorEventsRequest, OutgoingWebhookLogsRequest ); diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index c62de5bd29a..3f0febcc592 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -3,7 +3,8 @@ pub use analytics::*; pub mod routes { use actix_web::{web, Responder, Scope}; use analytics::{ - api_event::api_events_core, errors::AnalyticsError, lambda_utils::invoke_lambda, + api_event::api_events_core, connector_events::connector_events_core, + errors::AnalyticsError, lambda_utils::invoke_lambda, outgoing_webhook_event::outgoing_webhook_events_core, sdk_events::sdk_events_core, }; use api_models::analytics::{ @@ -71,6 +72,10 @@ pub mod routes { ) .service(web::resource("api_event_logs").route(web::get().to(get_api_events))) .service(web::resource("sdk_event_logs").route(web::post().to(get_sdk_events))) + .service( + web::resource("connector_event_logs") + .route(web::get().to(get_connector_events)), + ) .service( web::resource("outgoing_webhook_event_logs") .route(web::get().to(get_outgoing_webhook_events)), @@ -585,4 +590,26 @@ pub mod routes { )) .await } + + pub async fn get_connector_events( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Query<api_models::analytics::connector_events::ConnectorEventsRequest>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetConnectorEvents; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + connector_events_core(&state.pool, req, auth.merchant_account.merchant_id) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } } diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index 0127d07170f..9139b5eed41 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -52,6 +52,7 @@ pub enum AnalyticsFlow { GenerateRefundReport, GetApiEventMetrics, GetApiEventFilters, + GetConnectorEvents, GetOutgoingWebhookEvents, }
2024-01-10T20:00:48Z
## Description adding GET api for query to fetch connector events log by specified `payment_id` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
398c5ed51e0547504c3dfbd1d7c23568337e7d1c
``` curl 'http://localhost:8080/analytics/v1/connector_event_logs?type=Payment&payment_id=pay_yfkCogrWxVbB8O0biPkh' \ -H 'Accept: */*' \ -H 'Accept-Language: en-GB,en' \ -H 'Authorization: Bearer *' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Origin: http://localhost:9000' \ -H 'Referer: http://localhost:9000/' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-site' \ -H 'Sec-GPC: 1' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36' \ -H 'api-key: hyperswitch' \ -H 'sec-ch-ua: "Chromium";v="112", "Brave";v="112", "Not:A-Brand";v="99"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --compressed ``` `[{"merchant_id":"Allconnector123","payment_id":"pay_yfkCogrWxVbB8O0biPkh","connector_name":"stripe","request_id":"018cf773-0564-77e8-9e89-6870acfff2db","flow":"Authorize","request":"{\"amount\":6500,\"currency\":\"USD\",\"statement_descriptor_suffix\":null,\"statement_descriptor\":null,\"metadata[order_id]\":\"pay_yfkCogrWxVbB8O0biPkh_1\",\"metadata[is_refund_id_as_reference]\":null,\"return_url\":\"https://sandbox.hyperswitch.io/payments/pay_yfkCogrWxVbB8O0biPkh/Allconnector123/redirect/response/stripe\",\"confirm\":true,\"mandate\":null,\"payment_method\":null,\"customer\":\"*** alloc::string::String ***\",\"description\":\"Hello this is description\",\"shipping[address][city]\":\"Banglore\",\"shipping[address][country]\":\"US\",\"shipping[address][line1]\":\"*** alloc::string::String ***\",\"shipping[address][line2]\":\"*** alloc::string::String ***\",\"shipping[address][postal_code]\":\"*** alloc::string::String ***\",\"shipping[address][state]\":\"*** alloc::string::String ***\",\"shipping[name]\":\"*** alloc::string::String ***\",\"shipping[phone]\":\"*** alloc::string::String ***\",\"payment_method_data[billing_details][email]\":null,\"payment_method_data[billing_details][address][country]\":null,\"payment_method_data[billing_details][name]\":null,\"payment_method_data[billing_details][address][city]\":null,\"payment_method_data[billing_details][address][line1]\":null,\"payment_method_data[billing_details][address][line2]\":null,\"payment_method_data[billing_details][address][postal_code]\":null,\"payment_method_data[type]\":\"card\",\"payment_method_data[card][number]\":\"400000**********\",\"payment_method_data[card][exp_month]\":\"*** alloc::string::String ***\",\"payment_method_data[card][exp_year]\":\"*** alloc::string::String ***\",\"payment_method_data[card][cvc]\":\"*** alloc::string::String ***\",\"payment_method_options[card][request_three_d_secure]\":\"any\",\"capture_method\":\"automatic\",\"payment_method_options\":null,\"setup_future_usage\":null,\"off_session\":null,\"payment_method_types[0]\":\"card\"}","response":"{\\n \\\"id\\\": \\\"pi_3OXInzD5R7gDAGff1cGAxxHo\\\",\\n \\\"object\\\": \\\"payment_intent\\\",\\n \\\"amount\\\": 6500,\\n \\\"amount_capturable\\\": 0,\\n \\\"amount_details\\\": {\\n \\\"tip\\\": {}\\n },\\n \\\"amount_received\\\": 0,\\n \\\"application\\\": null,\\n \\\"application_fee_amount\\\": null,\\n \\\"automatic_payment_methods\\\": null,\\n \\\"canceled_at\\\": null,\\n \\\"cancellation_reason\\\": null,\\n \\\"capture_method\\\": \\\"automatic\\\",\\n \\\"client_secret\\\": \\\"pi_3OXInzD5R7gDAGff1cGAxxHo_secret_E2nuQt3TQz1PbCGT8B6MiWLGu\\\",\\n \\\"confirmation_method\\\": \\\"automatic\\\",\\n \\\"created\\\": 1704958559,\\n \\\"currency\\\": \\\"usd\\\",\\n \\\"customer\\\": \\\"cus_OuQL3sWtKEn0Cs\\\",\\n \\\"description\\\": \\\"Hello this is description\\\",\\n \\\"invoice\\\": null,\\n \\\"last_payment_error\\\": null,\\n \\\"latest_charge\\\": null,\\n \\\"livemode\\\": false,\\n \\\"metadata\\\": {\\n \\\"order_id\\\": \\\"pay_yfkCogrWxVbB8O0biPkh_1\\\"\\n },\\n \\\"next_action\\\": {\\n \\\"redirect_to_url\\\": {\\n \\\"return_url\\\": \\\"https://sandbox.hyperswitch.io/payments/pay_yfkCogrWxVbB8O0biPkh/Allconnector123/redirect/response/stripe\\\",\\n \\\"url\\\": \\\"https://hooks.stripe.com/redirect/authenticate/src_1OXIo0D5R7gDAGffxkofsikB?client_secret=src_client_secret_1P7sv3nHuAc684vjLZlUhwT1&source_redirect_slug=test_YWNjdF8xTTdmVGFENVI3Z0RBR2ZmLF9QTTBwNkJKN01LOWIzeFA3bkMxNjhCd2tra01oUnZ50100WMdcNcbT\\\"\\n },\\n \\\"type\\\": \\\"redirect_to_url\\\"\\n },\\n \\\"on_behalf_of\\\": null,\\n \\\"payment_method\\\": \\\"pm_1OXInzD5R7gDAGffpXWPgsBW\\\",\\n \\\"payment_method_configuration_details\\\": null,\\n \\\"payment_method_options\\\": {\\n \\\"card\\\": {\\n \\\"installments\\\": null,\\n \\\"mandate_options\\\": null,\\n \\\"network\\\": null,\\n \\\"request_three_d_secure\\\": \\\"any\\\"\\n }\\n },\\n \\\"payment_method_types\\\": [\\n \\\"card\\\"\\n ],\\n \\\"processing\\\": null,\\n \\\"receipt_email\\\": null,\\n \\\"review\\\": null,\\n \\\"setup_future_usage\\\": null,\\n \\\"shipping\\\": {\\n \\\"address\\\": {\\n \\\"city\\\": \\\"Banglore\\\",\\n \\\"country\\\": \\\"US\\\",\\n \\\"line1\\\": \\\"sdsdfsdf\\\",\\n \\\"line2\\\": \\\"hsgdbhd\\\",\\n \\\"postal_code\\\": \\\"571201\\\",\\n \\\"state\\\": \\\"zsaasdas\\\"\\n },\\n \\\"carrier\\\": null,\\n \\\"name\\\": \\\"Bopanna MJ\\\",\\n \\\"phone\\\": \\\"+1123456789\\\",\\n \\\"tracking_number\\\": null\\n },\\n \\\"source\\\": null,\\n \\\"statement_descriptor\\\": null,\\n \\\"statement_descriptor_suffix\\\": null,\\n \\\"status\\\": \\\"requires_action\\\",\\n \\\"transfer_data\\\": null,\\n \\\"transfer_group\\\": null\\n}","error":null,"status_code":0,"latency":891,"created_at":"2024-01-11T07:36:00.507Z","method":"POST"}]`
[ "crates/analytics/src/clickhouse.rs", "crates/analytics/src/connector_events.rs", "crates/analytics/src/connector_events/core.rs", "crates/analytics/src/connector_events/events.rs", "crates/analytics/src/lib.rs", "crates/analytics/src/sqlx.rs", "crates/analytics/src/types.rs", "crates/api_models/src/a...
juspay/hyperswitch
juspay__hyperswitch-3316
Bug: [REFACTOR] : [Bluesnap] Add connector_transaction_id as fallback for webhooks ### Bug Description Currently we are only consuming `merchant_transaction_id` from the webhook body, this was done to tackle the timeouts issue, but seems like Bluesnap doesn't always includes this id, so we need to add `connector_transaction_id` as fallback for webhook body ### Expected Behavior add `connector_transaction_id` as fallback for webhook body, so that even if merchant_transaction_id is not present webhook can be processed ### Actual Behavior Currently we are only consuming `merchant_transaction_id` from the webhook body, this was done to tackle the timeouts issue, but seems like Bluesnap doesn't always includes this id, so we need to add `connector_transaction_id` as fallback for webhook body ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index edcad00c983..e54d8320d0f 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -1043,11 +1043,19 @@ impl api::IncomingWebhook for Bluesnap { | bluesnap::BluesnapWebhookEvents::Charge | bluesnap::BluesnapWebhookEvents::Chargeback | bluesnap::BluesnapWebhookEvents::ChargebackStatusChanged => { - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::PaymentAttemptId( - webhook_body.merchant_transaction_id, - ), - )) + if webhook_body.merchant_transaction_id.is_empty() { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + webhook_body.reference_number, + ), + )) + } else { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::PaymentAttemptId( + webhook_body.merchant_transaction_id, + ), + )) + } } bluesnap::BluesnapWebhookEvents::Refund => { Ok(api_models::webhooks::ObjectReferenceId::RefundId(
2024-01-10T13:44:27Z
## Description <!-- Describe your changes in detail --> add connector_txn_id fallback for webhook ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3316 #
e0e28b87c0647252918ef110cd7614c46b5cf943
Trigger webhooks from Bluesnap with and without `merchant_transaction_id` and receive outgoing webhooks from Hyperswitch <img width="1424" alt="Screenshot 2024-01-10 at 7 13 24 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/5a743336-f53a-421f-9d23-d0e75344232d">
[ "crates/router/src/connector/bluesnap.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3309
Bug: [FEATURE] Add support for card extended bin in payment attempt ### Feature Description Card extended bin is initial 8 digit of card number. we need this field to be sent in payment attempt so that merchant can block payments based on this field too ### Possible Implementation Add a new field `card_extended_bin` in `AdditionalCardInfo` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 4ef0c540b51..7cc9296815b 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1129,6 +1129,7 @@ pub struct AdditionalCardInfo { pub bank_code: Option<String>, pub last4: Option<String>, pub card_isin: Option<String>, + pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, @@ -1665,6 +1666,7 @@ pub struct CardResponse { pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, + pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, @@ -1707,7 +1709,7 @@ pub enum VoucherData { #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { #[serde(rename = "card")] - Card(CardResponse), + Card(Box<CardResponse>), BankTransfer, Wallet, PayLater, @@ -2037,7 +2039,7 @@ pub struct PaymentsResponse { #[schema(example = 100)] pub amount: i64, - /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount, + /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount, /// If no surcharge_details, net_amount = amount #[schema(example = 110)] pub net_amount: i64, @@ -2528,6 +2530,7 @@ impl From<AdditionalCardInfo> for CardResponse { card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, + card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, @@ -2538,7 +2541,7 @@ impl From<AdditionalCardInfo> for CardResponse { impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { - AdditionalPaymentData::Card(card) => Self::Card(CardResponse::from(*card)), + AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater {} => Self::PayLater, AdditionalPaymentData::Wallet {} => Self::Wallet, AdditionalPaymentData::BankRedirect { .. } => Self::BankRedirect, diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index ca47c73c7c2..900f006eb4d 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -35,6 +35,9 @@ impl CardNumber { .rev() .collect::<String>() } + pub fn get_card_extended_bin(self) -> String { + self.0.peek().chars().take(8).collect::<String>() + } } impl FromStr for CardNumber { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index d864cacc52f..17cc608d82d 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3287,6 +3287,7 @@ pub async fn get_additional_payment_data( match pm_data { api_models::payments::PaymentMethodData::Card(card_data) => { let card_isin = Some(card_data.card_number.clone().get_card_isin()); + let card_extended_bin = Some(card_data.card_number.clone().get_card_extended_bin()); let last4 = Some(card_data.card_number.clone().get_last4()); if card_data.card_issuer.is_some() && card_data.card_network.is_some() @@ -3306,6 +3307,7 @@ pub async fn get_additional_payment_data( card_holder_name: card_data.card_holder_name.clone(), last4: last4.clone(), card_isin: card_isin.clone(), + card_extended_bin: card_extended_bin.clone(), }, )) } else { @@ -3329,6 +3331,7 @@ pub async fn get_additional_payment_data( card_issuing_country: card_info.card_issuing_country, last4: last4.clone(), card_isin: card_isin.clone(), + card_extended_bin: card_extended_bin.clone(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(), @@ -3344,6 +3347,7 @@ pub async fn get_additional_payment_data( card_issuing_country: None, last4, card_isin, + card_extended_bin, card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), card_holder_name: card_data.card_holder_name.clone(),
2024-01-10T11:22:12Z
## Description <!-- Describe your changes in detail --> Card extended bin is the initial 8 digits of card number. we need this field to be sent in payment attempt so that merchant can block payments based on this field too. This PR adds a new field `card_extended_bin` in `AdditionalCardInfo` struct which is mapped to `payment_method_data` in `payment_attempt` table. Also this field is added in payments retrieve response too. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
fe3cf54781302c733c1682ded2c1735544407a5f
1. Do a payment with card. You should be getting the `card_extended_bin` field in response ![image](https://github.com/juspay/hyperswitch/assets/70657455/ff2a0da3-ef7b-4415-9c15-e49bcd3f43f4) 2. Do a payment retrieve call using the `payment_id` from above call. You should get `card_extended_bin` field in response ![image](https://github.com/juspay/hyperswitch/assets/70657455/f8947f6b-bfbb-4a26-a4a6-8bf29c0d9a12)
[ "crates/api_models/src/payments.rs", "crates/cards/src/validate.rs", "crates/router/src/core/payments/helpers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3311
Bug: audit trail - add webhook events ### Webhook Events Audit trail Build a webhook events audit trail endpoint for fetching all events from `webhook_events_audit` table for ops audit trail. ![Image](https://github.com/juspay/hyperswitch/assets/21202349/3ae37c76-117e-46af-8e5c-3c9b74410efa) can refer to the existing API Events audit trail implementation [here](https://github.com/juspay/hyperswitch/blob/main/crates/analytics/src/api_event/events.rs) ``` curl --location 'https://sandbox.hyperswitch.io/analytics/v1/api_event_logs?type=Payment&payment_id=pay_yEsFwSqi6Umv8LVGFFPD' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjBmZDAyNzAtNTE1MS00MWVhLWJiMWItMGY0ZWExZGNmYjQzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjg5OTI0ODQzIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNzA0ODgyODg5LCJvcmdfaWQiOiJvcmdfRk5ZWjhQaE5CQjdtV1hodWxWQW0ifQ.LCgIW8uMGVo2WRFt2irzQ1D8sHuRBSbeRkTGt1qxsXM' ``` The API contract would involve a simple `GET analytics/v1/webhook_event_logs` path. with similar response format as above curl request
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 964486c9364..b8fd5e6a35d 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -21,6 +21,7 @@ use crate::{ filters::ApiEventFilter, metrics::{latency::LatencyAvg, ApiEventMetricRow}, }, + outgoing_webhook_event::events::OutgoingWebhookLogsResult, sdk_events::events::SdkEventsResult, types::TableEngine, }; @@ -120,6 +121,7 @@ impl AnalyticsDataSource for ClickhouseClient { } AnalyticsCollection::SdkEvents => TableEngine::BasicTree, AnalyticsCollection::ApiEvents => TableEngine::BasicTree, + AnalyticsCollection::OutgoingWebhookEvent => TableEngine::BasicTree, } } } @@ -145,6 +147,10 @@ impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {} impl super::api_event::events::ApiLogsFilterAnalytics for ClickhouseClient {} impl super::api_event::filters::ApiEventFilterAnalytics for ClickhouseClient {} impl super::api_event::metrics::ApiEventMetricAnalytics for ClickhouseClient {} +impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics + for ClickhouseClient +{ +} #[derive(Debug, serde::Serialize)] struct CkhQuery { @@ -302,6 +308,18 @@ impl TryInto<ApiEventFilter> for serde_json::Value { } } +impl TryInto<OutgoingWebhookLogsResult> for serde_json::Value { + type Error = Report<ParsingError>; + + fn try_into(self) -> Result<OutgoingWebhookLogsResult, Self::Error> { + serde_json::from_value(self) + .into_report() + .change_context(ParsingError::StructParseFailure( + "Failed to parse OutgoingWebhookLogsResult in clickhouse results", + )) + } +} + impl ToSql<ClickhouseClient> for PrimitiveDateTime { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { let format = @@ -326,6 +344,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { Self::SdkEvents => Ok("sdk_events_dist".to_string()), Self::ApiEvents => Ok("api_audit_log".to_string()), Self::PaymentIntent => Ok("payment_intents_dist".to_string()), + Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), } } } diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 24da77f84f2..8529807a1a1 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -7,6 +7,7 @@ mod query; pub mod refunds; pub mod api_event; +pub mod outgoing_webhook_event; pub mod sdk_events; mod sqlx; mod types; diff --git a/crates/analytics/src/outgoing_webhook_event.rs b/crates/analytics/src/outgoing_webhook_event.rs new file mode 100644 index 00000000000..9919d8bbb0f --- /dev/null +++ b/crates/analytics/src/outgoing_webhook_event.rs @@ -0,0 +1,6 @@ +mod core; +pub mod events; + +pub trait OutgoingWebhookEventAnalytics: events::OutgoingWebhookLogsFilterAnalytics {} + +pub use self::core::outgoing_webhook_events_core; diff --git a/crates/analytics/src/outgoing_webhook_event/core.rs b/crates/analytics/src/outgoing_webhook_event/core.rs new file mode 100644 index 00000000000..5024cc70ec1 --- /dev/null +++ b/crates/analytics/src/outgoing_webhook_event/core.rs @@ -0,0 +1,27 @@ +use api_models::analytics::outgoing_webhook_event::OutgoingWebhookLogsRequest; +use common_utils::errors::ReportSwitchExt; +use error_stack::{IntoReport, ResultExt}; + +use super::events::{get_outgoing_webhook_event, OutgoingWebhookLogsResult}; +use crate::{errors::AnalyticsResult, types::FiltersError, AnalyticsProvider}; + +pub async fn outgoing_webhook_events_core( + pool: &AnalyticsProvider, + req: OutgoingWebhookLogsRequest, + merchant_id: String, +) -> AnalyticsResult<Vec<OutgoingWebhookLogsResult>> { + let data = match pool { + AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented( + "Outgoing Webhook Events Logs not implemented for SQLX", + )) + .into_report() + .attach_printable("SQL Analytics is not implemented for Outgoing Webhook Events"), + AnalyticsProvider::Clickhouse(ckh_pool) + | AnalyticsProvider::CombinedSqlx(_, ckh_pool) + | AnalyticsProvider::CombinedCkh(_, ckh_pool) => { + get_outgoing_webhook_event(&merchant_id, req, ckh_pool).await + } + } + .switch()?; + Ok(data) +} diff --git a/crates/analytics/src/outgoing_webhook_event/events.rs b/crates/analytics/src/outgoing_webhook_event/events.rs new file mode 100644 index 00000000000..e742387e1eb --- /dev/null +++ b/crates/analytics/src/outgoing_webhook_event/events.rs @@ -0,0 +1,90 @@ +use api_models::analytics::{outgoing_webhook_event::OutgoingWebhookLogsRequest, Granularity}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use crate::{ + query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, +}; +pub trait OutgoingWebhookLogsFilterAnalytics: LoadRow<OutgoingWebhookLogsResult> {} + +pub async fn get_outgoing_webhook_event<T>( + merchant_id: &String, + query_param: OutgoingWebhookLogsRequest, + pool: &T, +) -> FiltersResult<Vec<OutgoingWebhookLogsResult>> +where + T: AnalyticsDataSource + OutgoingWebhookLogsFilterAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::OutgoingWebhookEvent); + query_builder.add_select_column("*").switch()?; + + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; + query_builder + .add_filter_clause("payment_id", query_param.payment_id) + .switch()?; + + if let Some(event_id) = query_param.event_id { + query_builder + .add_filter_clause("event_id", &event_id) + .switch()?; + } + if let Some(refund_id) = query_param.refund_id { + query_builder + .add_filter_clause("refund_id", &refund_id) + .switch()?; + } + if let Some(dispute_id) = query_param.dispute_id { + query_builder + .add_filter_clause("dispute_id", &dispute_id) + .switch()?; + } + if let Some(mandate_id) = query_param.mandate_id { + query_builder + .add_filter_clause("mandate_id", &mandate_id) + .switch()?; + } + if let Some(payment_method_id) = query_param.payment_method_id { + query_builder + .add_filter_clause("payment_method_id", &payment_method_id) + .switch()?; + } + if let Some(attempt_id) = query_param.attempt_id { + query_builder + .add_filter_clause("attempt_id", &attempt_id) + .switch()?; + } + //TODO!: update the execute_query function to return reports instead of plain errors... + query_builder + .execute_query::<OutgoingWebhookLogsResult, _>(pool) + .await + .change_context(FiltersError::QueryBuildingError)? + .change_context(FiltersError::QueryExecutionFailure) +} +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct OutgoingWebhookLogsResult { + pub merchant_id: String, + pub event_id: String, + pub event_type: String, + pub outgoing_webhook_event_type: String, + pub payment_id: String, + pub refund_id: Option<String>, + pub attempt_id: Option<String>, + pub dispute_id: Option<String>, + pub payment_method_id: Option<String>, + pub mandate_id: Option<String>, + pub content: Option<String>, + pub is_error: bool, + pub error: Option<String>, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: PrimitiveDateTime, +} diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index cdd2647e4e7..e32b85a5367 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -429,6 +429,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection { Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ApiEvents table is not implemented for Sqlx"))?, Self::PaymentIntent => Ok("payment_intent".to_string()), + Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?, } } } diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 8b1bdbd1ab9..8da4655e255 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -26,6 +26,7 @@ pub enum AnalyticsCollection { SdkEvents, ApiEvents, PaymentIntent, + OutgoingWebhookEvent, } #[allow(dead_code)] diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 0263427b0fd..e0d3fa671b6 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -12,6 +12,7 @@ use self::{ pub use crate::payments::TimeRange; pub mod api_event; +pub mod outgoing_webhook_event; pub mod payments; pub mod refunds; pub mod sdk_events; diff --git a/crates/api_models/src/analytics/outgoing_webhook_event.rs b/crates/api_models/src/analytics/outgoing_webhook_event.rs new file mode 100644 index 00000000000..b6f0aca056f --- /dev/null +++ b/crates/api_models/src/analytics/outgoing_webhook_event.rs @@ -0,0 +1,10 @@ +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct OutgoingWebhookLogsRequest { + pub payment_id: String, + pub event_id: Option<String>, + pub refund_id: Option<String>, + pub dispute_id: Option<String>, + pub mandate_id: Option<String>, + pub payment_method_id: Option<String>, + pub attempt_id: Option<String>, +} diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 457d3fde05b..6d9bd5db342 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -17,7 +17,9 @@ use common_utils::{ use crate::{ admin::*, - analytics::{api_event::*, sdk_events::*, *}, + analytics::{ + api_event::*, outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, *, + }, api_keys::*, cards_info::*, disputes::*, @@ -89,7 +91,8 @@ impl_misc_api_event_type!( ApiLogsRequest, GetApiEventMetricRequest, SdkEventsRequest, - ReportRequest + ReportRequest, + OutgoingWebhookLogsRequest ); #[cfg(feature = "stripe")] diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index f31e908e0dc..c62de5bd29a 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -4,7 +4,7 @@ pub mod routes { use actix_web::{web, Responder, Scope}; use analytics::{ api_event::api_events_core, errors::AnalyticsError, lambda_utils::invoke_lambda, - sdk_events::sdk_events_core, + outgoing_webhook_event::outgoing_webhook_events_core, sdk_events::sdk_events_core, }; use api_models::analytics::{ GenerateReportRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest, @@ -71,6 +71,10 @@ pub mod routes { ) .service(web::resource("api_event_logs").route(web::get().to(get_api_events))) .service(web::resource("sdk_event_logs").route(web::post().to(get_sdk_events))) + .service( + web::resource("outgoing_webhook_event_logs") + .route(web::get().to(get_outgoing_webhook_events)), + ) .service( web::resource("filters/api_events") .route(web::post().to(get_api_event_filters)), @@ -314,6 +318,30 @@ pub mod routes { .await } + pub async fn get_outgoing_webhook_events( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Query< + api_models::analytics::outgoing_webhook_event::OutgoingWebhookLogsRequest, + >, + ) -> impl Responder { + let flow = AnalyticsFlow::GetOutgoingWebhookEvents; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: AuthenticationData, req| async move { + outgoing_webhook_events_core(&state.pool, req, auth.merchant_account.merchant_id) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth(Permission::Analytics), + api_locking::LockAction::NotApplicable, + )) + .await + } + pub async fn get_sdk_events( state: web::Data<AppState>, req: actix_web::HttpRequest, diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index 3c7ba8b93df..0127d07170f 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -52,6 +52,7 @@ pub enum AnalyticsFlow { GenerateRefundReport, GetApiEventMetrics, GetApiEventFilters, + GetOutgoingWebhookEvents, } impl FlowMetric for AnalyticsFlow {}
2024-01-10T11:16:28Z
## Description adding GET api for query to fetch outgoing webhook events log by specified filters **Filter:** ```payment_id: String``` ```event_id: Option<String>``` ```refund_id: Option<String>``` ```dispute_id: Option<String>``` ```mandate_id: Option<String>``` ```payment_method_id: Option<String>``` ```attempt_id: Option<String>``` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
ed07c5ba90868a3132ca90d72219db3ba8978232
**Api Endpoint:** ```http://localhost:8080/analytics/v1/outgoing_webhook_event_logs``` curl attached below with sample response tested on local machine
[ "crates/analytics/src/clickhouse.rs", "crates/analytics/src/lib.rs", "crates/analytics/src/outgoing_webhook_event.rs", "crates/analytics/src/outgoing_webhook_event/core.rs", "crates/analytics/src/outgoing_webhook_event/events.rs", "crates/analytics/src/sqlx.rs", "crates/analytics/src/types.rs", "crate...
juspay/hyperswitch
juspay__hyperswitch-3307
Bug: [FEATURE] [BOA/Cybersource] Include merchant metadata in capture and void requests ### Feature Description Include merchant metadata in capture and void requests for connectors BOA and Cybersource. ### Possible Implementation Include merchant metadata in capture and void requests for connectors BOA and Cybersource. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 71a44b5a6e6..e024eb7a501 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -988,6 +988,8 @@ pub struct OrderInformation { pub struct BankOfAmericaCaptureRequest { order_information: OrderInformation, client_reference_information: ClientReferenceInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>> @@ -997,6 +999,10 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>> fn try_from( value: &BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { + let merchant_defined_information = + value.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); Ok(Self { order_information: OrderInformation { amount_details: Amount { @@ -1007,6 +1013,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>> client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), }, + merchant_defined_information, }) } } @@ -1016,6 +1023,9 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>> pub struct BankOfAmericaVoidRequest { client_reference_information: ClientReferenceInformation, reversal_information: ReversalInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, + // The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works! } #[derive(Debug, Serialize)] @@ -1032,6 +1042,10 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCancelRouterData>> fn try_from( value: &BankOfAmericaRouterData<&types::PaymentsCancelRouterData>, ) -> Result<Self, Self::Error> { + let merchant_defined_information = + value.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); Ok(Self { client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), @@ -1054,6 +1068,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCancelRouterData>> field_name: "Cancellation Reason", })?, }, + merchant_defined_information, }) } } diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index e46833d2ecd..bc69fb78129 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -837,6 +837,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> pub struct CybersourcePaymentsCaptureRequest { processing_information: ProcessingInformation, order_information: OrderInformationWithBill, + client_reference_information: ClientReferenceInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } #[derive(Debug, Serialize)] @@ -853,6 +856,10 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCaptureRouterData>> fn try_from( item: &CybersourceRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); Ok(Self { processing_information: ProcessingInformation { capture_options: Some(CaptureOptions { @@ -873,6 +880,10 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCaptureRouterData>> }, bill_to: None, }, + client_reference_information: ClientReferenceInformation { + code: Some(item.router_data.connector_request_reference_id.clone()), + }, + merchant_defined_information, }) } } @@ -918,6 +929,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout pub struct CybersourceVoidRequest { client_reference_information: ClientReferenceInformation, reversal_information: ReversalInformation, + #[serde(skip_serializing_if = "Option::is_none")] + merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, + // The connector documentation does not mention the merchantDefinedInformation field for Void requests. But this has been still added because it works! } #[derive(Debug, Serialize)] @@ -932,6 +946,10 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCancelRouterData>> for Cyber fn try_from( value: &CybersourceRouterData<&types::PaymentsCancelRouterData>, ) -> Result<Self, Self::Error> { + let merchant_defined_information = + value.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); Ok(Self { client_reference_information: ClientReferenceInformation { code: Some(value.router_data.connector_request_reference_id.clone()), @@ -954,6 +972,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCancelRouterData>> for Cyber field_name: "Cancellation Reason", })?, }, + merchant_defined_information, }) } } @@ -1591,6 +1610,7 @@ impl<F> #[serde(rename_all = "camelCase")] pub struct CybersourceRefundRequest { order_information: OrderInformation, + client_reference_information: ClientReferenceInformation, } impl<F> TryFrom<&CybersourceRouterData<&types::RefundsRouterData<F>>> for CybersourceRefundRequest { @@ -1605,6 +1625,9 @@ impl<F> TryFrom<&CybersourceRouterData<&types::RefundsRouterData<F>>> for Cybers currency: item.router_data.request.currency, }, }, + client_reference_information: ClientReferenceInformation { + code: Some(item.router_data.request.refund_id.clone()), + }, }) } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7b7d64a5f81..09bb203d939 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1223,6 +1223,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureD None => None, }, browser_info, + metadata: payment_data.payment_intent.metadata, }) } } @@ -1257,6 +1258,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelDa cancellation_reason: payment_data.payment_attempt.cancellation_reason, connector_meta: payment_data.payment_attempt.connector_metadata, browser_info, + metadata: payment_data.payment_intent.metadata, }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 2225c2965bc..7cd45a0192f 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -428,6 +428,8 @@ pub struct PaymentsCaptureData { pub multiple_capture_data: Option<MultipleCaptureRequestData>, pub connector_meta: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, + pub metadata: Option<pii::SecretSerdeValue>, + // This metadata is used to store the metadata shared during the payment intent request. } #[derive(Debug, Clone, Default)] @@ -542,6 +544,8 @@ pub struct PaymentsCancelData { pub cancellation_reason: Option<String>, pub connector_meta: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, + pub metadata: Option<pii::SecretSerdeValue>, + // This metadata is used to store the metadata shared during the payment intent request. } #[derive(Debug, Default, Clone)]
2024-01-10T11:09:41Z
## Description <!-- Describe your changes in detail --> Include merchant metadata in capture and void requests for connectors BOA and Cybersource. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3307 #
612f8d9d5f5bcba78aa64c3128cc72be0f2860ea
Testing can be done by creating 2 manual authorized payments for each BOA and Cybersource. While creating these payments you should pass metadata in the requests. ``` "metadata": { "count_tickets": 1, "transaction_number": "5590043" }, ``` Then you should void one payment and capture the other. You should then be able to see this metadata in merchantDefinedInformation in BOA/Cybersource Dashboard. ![image](https://github.com/juspay/hyperswitch/assets/41580413/4ce708b8-8714-4dd3-8535-c480fdac3f30)
[ "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cybersource/transformers.rs", "crates/router/src/core/payments/transformers.rs", "crates/router/src/types.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3306
Bug: [BUG] Validation for authtype and metadata in payment connector update ### Bug Description We are validating authtype and metadata while creating payment connector account, But we are not validating in update call. ### Expected Behavior When we try to update payment connector, we should validate authtype and metadata. ### Actual Behavior When we try to update payment connector, we are not validating authtype and metadata. ### Steps To Reproduce Try updating payment connector account with wrong metadata and authtype, It doesn't validate. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index e8593581126..fd4cae3a2b9 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1172,6 +1172,34 @@ pub async fn update_payment_connector( field_name: "connector_account_details".to_string(), expected_format: "auth_type and api_key".to_string(), })?; + let connector_name = mca.connector_name.as_ref(); + let connector_enum = api_models::enums::Connector::from_str(connector_name) + .into_report() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?; + validate_auth_and_metadata_type(connector_enum, &auth, &req.metadata).map_err( + |err| match *err.current_context() { + errors::ConnectorError::InvalidConnectorName => { + err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The connector name is invalid".to_string(), + }) + } + errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: format!("The {} is invalid", field_name), + }), + errors::ConnectorError::FailedToObtainAuthType => { + err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The auth type is invalid for the connector".to_string(), + }) + } + _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "The request body is invalid".to_string(), + }), + }, + )?; let (connector_status, disabled) = validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?;
2024-01-10T10:25:29Z
## Description <!-- Describe your changes in detail --> Adding validation for authtype and metadata in update payment connector call. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Adding validation for authtype and metadata in update payment connector call. #
01c2de223f60595d77c06a59a40dfe041e02cfee
1)Try passing wrong metadata for any connector in update payment connector call <img width="1160" alt="Screenshot 2024-01-10 at 3 51 20 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/8db585b6-9924-41a0-bf32-c3ee12dc5daa"> 2)Try passing wrong authtype for any connector in update payment connector call <img width="1160" alt="Screenshot 2024-01-10 at 3 51 52 PM" src="https://github.com/juspay/hyperswitch/assets/121822803/04d12c2b-5a39-4721-9e3a-8c521a6f99c6">
[ "crates/router/src/core/admin.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3268
Bug: Deep health check for Hyperswitch Scheduler Components to be verified in the check: - [x] RDS (PostgreSQL) - Connection to Database - State of Migration - [x] ElastiCache (Redis) - Connection to Redis - [x] Stream Insertion - [x] #3524 - [x] Clickhouse
diff --git a/Cargo.lock b/Cargo.lock index a1aabc89a04..f0334ce9cfc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5526,6 +5526,7 @@ dependencies = [ "external_services", "futures 0.3.28", "masking", + "num_cpus", "once_cell", "rand 0.8.5", "redis_interface", diff --git a/config/config.example.toml b/config/config.example.toml index f7e9fa70f6e..fc5d4a3a039 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -298,6 +298,12 @@ lower_fetch_limit = 1800 # Lower limit for fetching entries from redis lock_key = "PRODUCER_LOCKING_KEY" # The following keys defines the producer lock that is created in redis with lock_ttl = 160 # the ttl being the expiry (in seconds) +# Scheduler server configuration +[scheduler.server] +port = 3000 # Port on which the server will listen for incoming requests +host = "127.0.0.1" # Host IP address to bind the server to +workers = 1 # Number of actix workers to handle incoming requests concurrently + batch_size = 200 # Specifies the batch size the producer will push under a single entry in the redis queue # Drainer configuration, which handles draining raw SQL queries from Redis streams to the SQL database diff --git a/config/deployments/scheduler/consumer.toml b/config/deployments/scheduler/consumer.toml index 907e3b8297e..cdd60552668 100644 --- a/config/deployments/scheduler/consumer.toml +++ b/config/deployments/scheduler/consumer.toml @@ -9,3 +9,9 @@ stream = "scheduler_stream" [scheduler.consumer] consumer_group = "scheduler_group" disabled = false # This flag decides if the consumer should actively consume task + +# Scheduler server configuration +[scheduler.server] +port = 3000 # Port on which the server will listen for incoming requests +host = "127.0.0.1" # Host IP address to bind the server to +workers = 1 # Number of actix workers to handle incoming requests concurrently diff --git a/config/deployments/scheduler/producer.toml b/config/deployments/scheduler/producer.toml index 579466a23cc..9cbaee96f03 100644 --- a/config/deployments/scheduler/producer.toml +++ b/config/deployments/scheduler/producer.toml @@ -12,3 +12,9 @@ lock_key = "producer_locking_key" # The following keys defines the producer lock lock_ttl = 160 # the ttl being the expiry (in seconds) lower_fetch_limit = 900 # Lower limit for fetching entries from redis queue (in seconds) upper_fetch_limit = 0 # Upper limit for fetching entries from the redis queue (in seconds)0 + +# Scheduler server configuration +[scheduler.server] +port = 3000 # Port on which the server will listen for incoming requests +host = "127.0.0.1" # Host IP address to bind the server to +workers = 1 # Number of actix workers to handle incoming requests concurrently diff --git a/config/development.toml b/config/development.toml index 584bdf751a2..20abb7bd6f3 100644 --- a/config/development.toml +++ b/config/development.toml @@ -228,6 +228,11 @@ stream = "SCHEDULER_STREAM" disabled = false consumer_group = "SCHEDULER_GROUP" +[scheduler.server] +port = 3000 +host = "127.0.0.1" +workers = 1 + [email] sender_email = "example@example.com" aws_region = "" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 67fca85929d..d14b7c1b740 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -227,6 +227,11 @@ stream = "SCHEDULER_STREAM" disabled = false consumer_group = "SCHEDULER_GROUP" +[scheduler.server] +port = 3000 +host = "127.0.0.1" +workers = 1 + #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs index 8323f135134..eab971b5fe1 100644 --- a/crates/api_models/src/health_check.rs +++ b/crates/api_models/src/health_check.rs @@ -8,3 +8,10 @@ pub struct RouterHealthCheckResponse { } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct SchedulerHealthCheckResponse { + pub database: bool, + pub redis: bool, +} + +impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {} diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index b800ecb897e..5f98cd88014 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -1,21 +1,29 @@ #![recursion_limit = "256"] use std::{str::FromStr, sync::Arc}; +use actix_web::{dev::Server, web, Scope}; +use api_models::health_check::SchedulerHealthCheckResponse; use common_utils::ext_traits::{OptionExt, StringExt}; use diesel_models::process_tracker as storage; use error_stack::ResultExt; use router::{ configs::settings::{CmdLineConf, Settings}, - core::errors::{self, CustomResult}, - logger, routes, services, + core::{ + errors::{self, CustomResult}, + health_check::HealthCheckInterface, + }, + logger, routes, + services::{self, api}, types::storage::ProcessTrackerExt, workflows, }; +use router_env::{instrument, tracing}; use scheduler::{ consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError, workflows::ProcessTrackerWorkflows, SchedulerAppState, }; use serde::{Deserialize, Serialize}; +use storage_impl::errors::ApplicationError; use strum::EnumString; use tokio::sync::{mpsc, oneshot}; @@ -68,6 +76,19 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { [router_env::service_name!()], ); + #[allow(clippy::expect_used)] + let web_server = Box::pin(start_web_server( + state.clone(), + scheduler_flow_str.to_string(), + )) + .await + .expect("Failed to create the server"); + + tokio::spawn(async move { + let _ = web_server.await; + logger::error!("The health check probe stopped working!"); + }); + logger::debug!(startup_config=?state.conf); start_scheduler(&state, scheduler_flow, (tx, rx)).await?; @@ -76,6 +97,106 @@ async fn main() -> CustomResult<(), ProcessTrackerError> { Ok(()) } +pub async fn start_web_server( + state: routes::AppState, + service: String, +) -> errors::ApplicationResult<Server> { + let server = state + .conf + .scheduler + .as_ref() + .ok_or(ApplicationError::InvalidConfigurationValueError( + "Scheduler server is invalidly configured".into(), + ))? + .server + .clone(); + + let web_server = actix_web::HttpServer::new(move || { + actix_web::App::new().service(Health::server(state.clone(), service.clone())) + }) + .bind((server.host.as_str(), server.port))? + .workers(server.workers) + .run(); + let _ = web_server.handle(); + + Ok(web_server) +} + +pub struct Health; + +impl Health { + pub fn server(state: routes::AppState, service: String) -> Scope { + web::scope("health") + .app_data(web::Data::new(state)) + .app_data(web::Data::new(service)) + .service(web::resource("").route(web::get().to(health))) + .service(web::resource("/ready").route(web::get().to(deep_health_check))) + } +} + +#[instrument(skip_all)] +pub async fn health() -> impl actix_web::Responder { + logger::info!("Scheduler health was called"); + actix_web::HttpResponse::Ok().body("Scheduler health is good") +} +#[instrument(skip_all)] +pub async fn deep_health_check( + state: web::Data<routes::AppState>, + service: web::Data<String>, +) -> impl actix_web::Responder { + let report = deep_health_check_func(state, service).await; + match report { + Ok(response) => services::http_response_json( + serde_json::to_string(&response) + .map_err(|err| { + logger::error!(serialization_error=?err); + }) + .unwrap_or_default(), + ), + Err(err) => api::log_and_return_error_response(err), + } +} +#[instrument(skip_all)] +pub async fn deep_health_check_func( + state: web::Data<routes::AppState>, + service: web::Data<String>, +) -> errors::RouterResult<SchedulerHealthCheckResponse> { + logger::info!("{} deep health check was called", service.into_inner()); + + logger::debug!("Database health check begin"); + + let db_status = state.health_check_db().await.map(|_| true).map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Database", + message: err.to_string() + }) + })?; + + logger::debug!("Database health check end"); + + logger::debug!("Redis health check begin"); + + let redis_status = state + .health_check_redis() + .await + .map(|_| true) + .map_err(|err| { + error_stack::report!(errors::ApiErrorResponse::HealthCheckError { + component: "Redis", + message: err.to_string() + }) + })?; + + logger::debug!("Redis health check end"); + + let response = SchedulerHealthCheckResponse { + database: db_status, + redis: redis_status, + }; + + Ok(response) +} + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, EnumString)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index 023e1f4b7fb..e83483b0816 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -238,7 +238,7 @@ pub enum ApiErrorResponse { WebhookInvalidMerchantSecret, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")] CurrencyNotSupported { message: String }, - #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failiing with error: {message}")] + #[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")] HealthCheckError { component: &'static str, message: String, diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml index fe090552edb..7d4a7821fc9 100644 --- a/crates/scheduler/Cargo.toml +++ b/crates/scheduler/Cargo.toml @@ -13,6 +13,7 @@ kv_store = [] async-trait = "0.1.68" error-stack = "0.3.1" futures = "0.3.28" +num_cpus = "1.15.0" once_cell = "1.18.0" rand = "0.8.5" serde = "1.0.193" diff --git a/crates/scheduler/src/configs/defaults.rs b/crates/scheduler/src/configs/defaults.rs index 25eb19e24f2..d17c20829ea 100644 --- a/crates/scheduler/src/configs/defaults.rs +++ b/crates/scheduler/src/configs/defaults.rs @@ -6,6 +6,7 @@ impl Default for super::settings::SchedulerSettings { consumer: super::settings::ConsumerSettings::default(), graceful_shutdown_interval: 60000, loop_interval: 5000, + server: super::settings::Server::default(), } } } @@ -30,3 +31,13 @@ impl Default for super::settings::ConsumerSettings { } } } + +impl Default for super::settings::Server { + fn default() -> Self { + Self { + port: 8080, + workers: num_cpus::get_physical(), + host: "localhost".into(), + } + } +} diff --git a/crates/scheduler/src/configs/settings.rs b/crates/scheduler/src/configs/settings.rs index 56a9f4079ac..723ef81e70c 100644 --- a/crates/scheduler/src/configs/settings.rs +++ b/crates/scheduler/src/configs/settings.rs @@ -15,6 +15,15 @@ pub struct SchedulerSettings { pub consumer: ConsumerSettings, pub loop_interval: u64, pub graceful_shutdown_interval: u64, + pub server: Server, +} + +#[derive(Debug, Deserialize, Clone)] +#[serde(default)] +pub struct Server { + pub port: u16, + pub workers: usize, + pub host: String, } #[derive(Debug, Clone, Deserialize)] diff --git a/crates/scheduler/src/configs/validations.rs b/crates/scheduler/src/configs/validations.rs index e9f6621b2a5..06052f9ff6c 100644 --- a/crates/scheduler/src/configs/validations.rs +++ b/crates/scheduler/src/configs/validations.rs @@ -19,6 +19,8 @@ impl super::settings::SchedulerSettings { self.producer.validate()?; + self.server.validate()?; + Ok(()) } } @@ -32,3 +34,13 @@ impl super::settings::ProducerSettings { }) } } + +impl super::settings::Server { + pub fn validate(&self) -> Result<(), ApplicationError> { + common_utils::fp_utils::when(self.host.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "server host must not be empty".into(), + )) + }) + } +}
2024-01-10T10:08:09Z
## Description <!-- Describe your changes in detail --> This PR adds support for performing a deeper health check of the scheduler which includes: Database connection check with read, write and delete queries (Added support for database transaction too) Redis connection check with set, get and delete key (Set key with expiry of 30sec) The deep health check API returns a 200 status code if all the components are in good health, but returns 500 if at least one component's health is down ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
20efc3020ac389199eed13154f070685417ef82a
1. `/health` ![image](https://github.com/juspay/hyperswitch/assets/70657455/fe87da30-d4ce-424d-9263-ad76a901f90f) 2. `/health/ready` ![image](https://github.com/juspay/hyperswitch/assets/70657455/922b18b9-006e-403f-93e7-714791c7434b) 3. `'health/ready` with some db error ![image](https://github.com/juspay/hyperswitch/assets/70657455/8def285d-dac3-4804-a7a6-1d67481b1ed0) Cannot be tested on sandbox as the endpoint is not exposed
[ "Cargo.lock", "config/config.example.toml", "config/deployments/scheduler/consumer.toml", "config/deployments/scheduler/producer.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/health_check.rs", "crates/router/src/bin/scheduler.rs", "crates/router/src/core/erro...
juspay/hyperswitch
juspay__hyperswitch-3292
Bug: Throw an error when outgoing webhook events env var not found
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 2b29a61b4a4..2bcfcfe974f 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -126,6 +126,15 @@ impl KafkaSettings { )) })?; + common_utils::fp_utils::when( + self.outgoing_webhook_logs_topic.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "Kafka Outgoing Webhook Logs topic must not be empty".into(), + )) + }, + )?; + Ok(()) } }
2024-01-09T07:44:10Z
## Description Throw an error when outgoing webhook events env var not found ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
ecf51b5e3a30f055634edfafcd36f64cef535a53
[ "crates/router/src/services/kafka.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3296
Bug: [FEATURE]: [Cybersource] Add 3DS flow for cards ### Feature Description Add 3DS flow for cards ### Possible Implementation Add 3DS flow for cards ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 94f71fa3f70..e20f9c1b65d 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -351,6 +351,7 @@ stripe = { payment_method = "bank_transfer" } nuvei = { payment_method = "card" } shift4 = { payment_method = "card" } bluesnap = { payment_method = "card" } +cybersource = {payment_method = "card"} nmi = {payment_method = "card"} [dummy_connector] diff --git a/config/development.toml b/config/development.toml index 272b3641713..5732d5f0d1d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -428,6 +428,7 @@ stripe = {payment_method = "bank_transfer"} nuvei = {payment_method = "card"} shift4 = {payment_method = "card"} bluesnap = {payment_method = "card"} +cybersource = {payment_method = "card"} nmi = {payment_method = "card"} [connector_customer] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index e55353f8903..c6934a64671 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -241,6 +241,7 @@ stripe = {payment_method = "bank_transfer"} nuvei = {payment_method = "card"} shift4 = {payment_method = "card"} bluesnap = {payment_method = "card"} +cybersource = {payment_method = "card"} nmi = {payment_method = "card"} [dummy_connector] diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 6c4ea4c61fe..69159c10c8a 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -12,6 +12,7 @@ use time::OffsetDateTime; use transformers as cybersource; use url::Url; +use super::utils::{PaymentsAuthorizeRequestData, RouterData}; use crate::{ configs::settings, connector::{utils as connector_utils, utils::RefundsRequestData}, @@ -286,6 +287,8 @@ impl api::PaymentIncrementalAuthorization for Cybersource {} impl api::MandateSetup for Cybersource {} impl api::ConnectorAccessToken for Cybersource {} impl api::PaymentToken for Cybersource {} +impl api::PaymentsPreProcessing for Cybersource {} +impl api::PaymentsCompleteAuthorize for Cybersource {} impl api::ConnectorMandateRevoke for Cybersource {} impl @@ -472,6 +475,113 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme { } +impl + ConnectorIntegration< + api::PreProcessing, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + > for Cybersource +{ + fn get_headers( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let redirect_response = req.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => Ok(format!( + "{}risk/v1/authentications", + self.base_url(connectors) + )), + Some(_) | None => Ok(format!( + "{}risk/v1/authentication-results", + self.base_url(connectors) + )), + } + } + fn get_request_body( + &self, + req: &types::PaymentsPreProcessingRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = cybersource::CybersourceRouterData::try_from(( + &self.get_currency_unit(), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + req.request + .amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "amount", + })?, + req, + ))?; + let connector_req = + cybersource::CybersourcePreProcessingRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsPreProcessingRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsPreProcessingType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsPreProcessingType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPreProcessingType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsPreProcessingRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { + let response: cybersource::CybersourcePreProcessingResponse = res + .response + .parse_struct("Cybersource AuthEnrollmentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Cybersource { @@ -672,13 +782,20 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}pts/v2/payments/", - api::ConnectorCommon::base_url(self, connectors) - )) + if req.is_three_ds() && req.request.is_card() { + Ok(format!( + "{}risk/v1/authentication-setups", + api::ConnectorCommon::base_url(self, connectors) + )) + } else { + Ok(format!( + "{}pts/v2/payments/", + api::ConnectorCommon::base_url(self, connectors) + )) + } } fn get_request_body( @@ -692,9 +809,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req.request.amount, req, ))?; - let connector_req = - cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + if req.is_three_ds() && req.request.is_card() { + let connector_req = + cybersource::CybersourceAuthSetupRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } else { + let connector_req = + cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } } fn build_request( @@ -722,6 +845,106 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + if data.is_three_ds() && data.request.is_card() { + let response: cybersource::CybersourceAuthSetupResponse = res + .response + .parse_struct("Cybersource AuthSetupResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } else { + let response: cybersource::CybersourcePaymentsResponse = res + .response + .parse_struct("Cybersource PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + } + + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl + ConnectorIntegration< + api::CompleteAuthorize, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + > for Cybersource +{ + fn get_headers( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + _req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}pts/v2/payments/", + api::ConnectorCommon::base_url(self, connectors) + )) + } + fn get_request_body( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_router_data = cybersource::CybersourceRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = + cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( + &self, + req: &types::PaymentsCompleteAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &types::PaymentsCompleteAuthorizeRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: cybersource::CybersourcePaymentsResponse = res .response .parse_struct("Cybersource PaymentResponse") diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 8ae2ce29e5b..e83b23603e9 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1,6 +1,7 @@ use api_models::payments; use base64::Engine; -use common_utils::pii; +use common_utils::{ext_traits::ValueExt, pii}; +use error_stack::{IntoReport, ResultExt}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -8,10 +9,12 @@ use serde_json::Value; use crate::{ connector::utils::{ self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData, + PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RouterData, }, consts, core::errors, + services, types::{ self, api::{self, enums as api_enums}, @@ -200,7 +203,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { action_list, action_token_types, authorization_options, - commerce_indicator: CybersourceCommerceIndicator::Internet, + commerce_indicator: String::from("internet"), payment_solution: solution.map(String::from), }; Ok(Self { @@ -220,6 +223,8 @@ pub struct CybersourcePaymentsRequest { order_information: OrderInformationWithBill, client_reference_information: ClientReferenceInformation, #[serde(skip_serializing_if = "Option::is_none")] + consumer_authentication_information: Option<CybersourceConsumerAuthInformation>, + #[serde(skip_serializing_if = "Option::is_none")] merchant_defined_information: Option<Vec<MerchantDefinedInformation>>, } @@ -229,12 +234,22 @@ pub struct ProcessingInformation { action_list: Option<Vec<CybersourceActionsList>>, action_token_types: Option<Vec<CybersourceActionsTokenType>>, authorization_options: Option<CybersourceAuthorizationOptions>, - commerce_indicator: CybersourceCommerceIndicator, + commerce_indicator: String, capture: Option<bool>, capture_options: Option<CaptureOptions>, payment_solution: Option<String>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformation { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + directory_server_transaction_id: Option<String>, + specification_version: Option<String>, +} #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct MerchantDefinedInformation { @@ -282,12 +297,6 @@ pub enum CybersourcePaymentInitiatorTypes { Customer, } -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub enum CybersourceCommerceIndicator { - Internet, -} - #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CaptureOptions { @@ -450,6 +459,16 @@ impl From<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> } } +impl From<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for ClientReferenceInformation +{ + fn from(item: &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>) -> Self { + Self { + code: Some(item.router_data.connector_request_reference_id.clone()), + } + } +} + impl From<( &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, @@ -489,7 +508,56 @@ impl action_token_types, authorization_options, capture_options: None, - commerce_indicator: CybersourceCommerceIndicator::Internet, + commerce_indicator: String::from("internet"), + } + } +} + +impl + From<( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &CybersourceConsumerAuthValidateResponse, + )> for ProcessingInformation +{ + fn from( + (item, solution, three_ds_data): ( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + Option<PaymentSolution>, + &CybersourceConsumerAuthValidateResponse, + ), + ) -> Self { + let (action_list, action_token_types, authorization_options) = + if item.router_data.request.setup_future_usage.is_some() { + ( + Some(vec![CybersourceActionsList::TokenCreate]), + Some(vec![CybersourceActionsTokenType::PaymentInstrument]), + Some(CybersourceAuthorizationOptions { + initiator: CybersourcePaymentInitiator { + initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), + credential_stored_on_file: Some(true), + stored_credential_used: None, + }, + merchant_intitiated_transaction: None, + }), + ) + } else { + (None, None, None) + }; + Self { + capture: Some(matches!( + item.router_data.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + )), + payment_solution: solution.map(String::from), + action_list, + action_token_types, + authorization_options, + capture_options: None, + commerce_indicator: three_ds_data + .indicator + .to_owned() + .unwrap_or(String::from("internet")), } } } @@ -516,6 +584,28 @@ impl } } +impl + From<( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + )> for OrderInformationWithBill +{ + fn from( + (item, bill_to): ( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + BillTo, + ), + ) -> Self { + Self { + amount_details: Amount { + total_amount: item.amount.to_owned(), + currency: item.router_data.request.currency, + }, + bill_to: Some(bill_to), + } + } +} + // for cybersource each item in Billing is mandatory fn build_bill_to( address_details: &payments::Address, @@ -602,6 +692,84 @@ impl payment_information, order_information, client_reference_information, + consumer_authentication_information: None, + merchant_defined_information, + }) + } +} + +impl + TryFrom<( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + )> for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, ccard): ( + &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + payments::Card, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + + let three_ds_info: CybersourceThreeDSMetadata = item + .router_data + .request + .connector_meta + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "connector_meta", + })? + .parse_value("CybersourceThreeDSMetadata") + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "Merchant connector account metadata", + })?; + + let processing_information = + ProcessingInformation::from((item, None, &three_ds_info.three_ds_data)); + + let consumer_authentication_information = Some(CybersourceConsumerAuthInformation { + ucaf_collection_indicator: three_ds_info.three_ds_data.ucaf_collection_indicator, + cavv: three_ds_info.three_ds_data.cavv, + ucaf_authentication_data: three_ds_info.three_ds_data.ucaf_authentication_data, + xid: three_ds_info.three_ds_data.xid, + directory_server_transaction_id: three_ds_info + .three_ds_data + .directory_server_transaction_id, + specification_version: three_ds_info.three_ds_data.specification_version, + }); + + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information, merchant_defined_information, }) } @@ -647,6 +815,7 @@ impl payment_information, order_information, client_reference_information, + consumer_authentication_information: None, merchant_defined_information, }) } @@ -689,6 +858,7 @@ impl payment_information, order_information, client_reference_information, + consumer_authentication_information: None, merchant_defined_information, }) } @@ -747,6 +917,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } } @@ -810,6 +981,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> order_information, client_reference_information, merchant_defined_information, + consumer_authentication_information: None, }) } payments::PaymentMethodData::CardRedirect(_) @@ -832,6 +1004,64 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> } } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceAuthSetupRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, +} + +impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> + for CybersourceAuthSetupRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }); + let client_reference_information = ClientReferenceInformation::from(item); + Ok(Self { + payment_information, + client_reference_information, + }) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ) + .into()) + } + } + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsCaptureRequest { @@ -870,7 +1100,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCaptureRouterData>> action_token_types: None, authorization_options: None, capture: None, - commerce_indicator: CybersourceCommerceIndicator::Internet, + commerce_indicator: String::from("internet"), payment_solution: None, }, order_information: OrderInformationWithBill { @@ -909,7 +1139,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRout reason: "5".to_owned(), }), }), - commerce_indicator: CybersourceCommerceIndicator::Internet, + commerce_indicator: String::from("internet"), capture: None, capture_options: None, payment_solution: None, @@ -1118,6 +1348,29 @@ pub struct CybersourceErrorInformationResponse { error_information: CybersourceErrorInformation, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformationResponse { + access_token: String, + device_data_collection_url: String, + reference_id: String, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthSetupInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: CybersourceConsumerAuthInformationResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum CybersourceAuthSetupResponse { + ClientAuthSetupInfo(ClientAuthSetupInfoResponse), + ErrorInformation(CybersourceErrorInformationResponse), +} + #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CybersourcePaymentsIncrementalAuthorizationResponse { @@ -1326,6 +1579,492 @@ impl<F> } } +impl<F> + TryFrom< + types::ResponseRouterData< + F, + CybersourceAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + CybersourceAuthSetupResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourceAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self { + status: enums::AttemptStatus::AuthenticationPending, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: Some(services::RedirectForm::CybersourceAuthSetup { + access_token: info_response + .consumer_authentication_information + .access_token, + ddc_url: info_response + .consumer_authentication_information + .device_data_collection_url, + reference_id: info_response + .consumer_authentication_information + .reference_id, + }), + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ), + incremental_authorization_allowed: None, + }), + ..item.data + }), + CybersourceAuthSetupResponse::ErrorInformation(error_response) => { + let error_reason = error_response + .error_information + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason; + Ok(Self { + response: Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }), + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformationRequest { + return_url: String, + reference_id: String, +} +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceAuthEnrollmentRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: CybersourceConsumerAuthInformationRequest, + order_information: OrderInformationWithBill, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub struct CybersourceRedirectionAuthResponse { + pub transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformationValidateRequest { + authentication_transaction_id: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceAuthValidateRequest { + payment_information: PaymentInformation, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: CybersourceConsumerAuthInformationValidateRequest, + order_information: OrderInformation, +} + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum CybersourcePreProcessingRequest { + AuthEnrollment(CybersourceAuthEnrollmentRequest), + AuthValidate(CybersourceAuthValidateRequest), +} + +impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>> + for CybersourcePreProcessingRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CybersourceRouterData<&types::PaymentsPreProcessingRouterData>, + ) -> Result<Self, Self::Error> { + let client_reference_information = ClientReferenceInformation { + code: Some(item.router_data.connector_request_reference_id.clone()), + }; + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "payment_method_data", + }, + )?; + let payment_information = match payment_method_data { + payments::PaymentMethodData::Card(ccard) => { + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + Ok(PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + })) + } + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + )) + } + }?; + + let redirect_response = item.router_data.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + + let amount_details = Amount { + total_amount: item.amount.clone(), + currency: item.router_data.request.currency.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "currency", + }, + )?, + }; + + match redirect_response.params { + Some(param) if !param.clone().peek().is_empty() => { + let reference_id = param + .clone() + .peek() + .split_once('=') + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.params.reference_id", + })? + .1 + .to_string(); + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill { + amount_details, + bill_to: Some(bill_to), + }; + Ok(Self::AuthEnrollment(CybersourceAuthEnrollmentRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + CybersourceConsumerAuthInformationRequest { + return_url: item.router_data.request.get_complete_authorize_url()?, + reference_id, + }, + order_information, + })) + } + Some(_) | None => { + let redirect_payload: CybersourceRedirectionAuthResponse = redirect_response + .payload + .ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload { + field_name: "request.redirect_response.payload", + })? + .peek() + .clone() + .parse_value("CybersourceRedirectionAuthResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let order_information = OrderInformation { amount_details }; + Ok(Self::AuthValidate(CybersourceAuthValidateRequest { + payment_information, + client_reference_information, + consumer_authentication_information: + CybersourceConsumerAuthInformationValidateRequest { + authentication_transaction_id: redirect_payload.transaction_id, + }, + order_information, + })) + } + } + } +} + +impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>> + for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_data", + }, + )?; + match payment_method_data { + payments::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)), + payments::PaymentMethodData::Wallet(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ) + .into()) + } + } + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum CybersourceAuthEnrollmentStatus { + PendingAuthentication, + AuthenticationSuccessful, + AuthenticationFailed, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthValidateResponse { + ucaf_collection_indicator: Option<String>, + cavv: Option<String>, + ucaf_authentication_data: Option<String>, + xid: Option<String>, + specification_version: Option<String>, + directory_server_transaction_id: Option<String>, + indicator: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct CybersourceThreeDSMetadata { + three_ds_data: CybersourceConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceConsumerAuthInformationEnrollmentResponse { + access_token: Option<String>, + step_up_url: Option<String>, + //Added to segregate the three_ds_data in a separate struct + #[serde(flatten)] + validate_response: CybersourceConsumerAuthValidateResponse, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientAuthCheckInfoResponse { + id: String, + client_reference_information: ClientReferenceInformation, + consumer_authentication_information: CybersourceConsumerAuthInformationEnrollmentResponse, + status: CybersourceAuthEnrollmentStatus, + error_information: Option<CybersourceErrorInformation>, +} + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum CybersourcePreProcessingResponse { + ClientAuthCheckInfo(Box<ClientAuthCheckInfoResponse>), + ErrorInformation(CybersourceErrorInformationResponse), +} + +impl From<CybersourceAuthEnrollmentStatus> for enums::AttemptStatus { + fn from(item: CybersourceAuthEnrollmentStatus) -> Self { + match item { + CybersourceAuthEnrollmentStatus::PendingAuthentication => Self::AuthenticationPending, + CybersourceAuthEnrollmentStatus::AuthenticationSuccessful => { + Self::AuthenticationSuccessful + } + CybersourceAuthEnrollmentStatus::AuthenticationFailed => Self::AuthenticationFailed, + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + CybersourcePreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + CybersourcePreProcessingResponse, + types::PaymentsPreProcessingData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourcePreProcessingResponse::ClientAuthCheckInfo(info_response) => { + let status = enums::AttemptStatus::from(info_response.status); + let risk_info: Option<ClientRiskInformation> = None; + if utils::is_payment_failure(status) { + let response = Err(types::ErrorResponse::from(( + &info_response.error_information, + &risk_info, + item.http_code, + info_response.id.clone(), + ))); + + Ok(Self { + status, + response, + ..item.data + }) + } else { + let connector_response_reference_id = Some( + info_response + .client_reference_information + .code + .unwrap_or(info_response.id.clone()), + ); + + let redirection_data = match ( + info_response + .consumer_authentication_information + .access_token, + info_response + .consumer_authentication_information + .step_up_url, + ) { + (Some(access_token), Some(step_up_url)) => { + Some(services::RedirectForm::CybersourceConsumerAuth { + access_token, + step_up_url, + }) + } + _ => None, + }; + let three_ds_data = serde_json::to_value( + info_response + .consumer_authentication_information + .validate_response, + ) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data, + mandate_reference: None, + connector_metadata: Some( + serde_json::json!({"three_ds_data":three_ds_data}), + ), + network_txn_id: None, + connector_response_reference_id, + incremental_authorization_allowed: None, + }), + ..item.data + }) + } + } + CybersourcePreProcessingResponse::ErrorInformation(ref error_response) => { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + Ok(Self { + response, + status: enums::AttemptStatus::AuthenticationFailed, + ..item.data + }) + } + } + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + CybersourcePaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + CybersourcePaymentsResponse, + types::CompleteAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response { + CybersourcePaymentsResponse::ClientReferenceInformation(info_response) => { + let status = enums::AttemptStatus::foreign_from(( + info_response.status.clone(), + item.data.request.is_auto_capture()?, + )); + let response = get_payment_response((&info_response, status, item.http_code)); + Ok(Self { + status, + response, + ..item.data + }) + } + CybersourcePaymentsResponse::ErrorInformation(ref error_response) => Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))), + } + } +} + impl<F> TryFrom< types::ResponseRouterData< @@ -1463,25 +2202,29 @@ impl<F, T> ..item.data }) } - CybersourceSetupMandatesResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id.clone()), - }) - }, - status: enums::AttemptStatus::Failure, - ..item.data - }), + CybersourceSetupMandatesResponse::ErrorInformation(ref error_response) => { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + Ok(Self { + response, + status: enums::AttemptStatus::Failure, + ..item.data + }) + } } } } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 55173f9b339..1040f020839 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -273,6 +273,7 @@ pub trait PaymentsPreProcessingData { fn get_webhook_url(&self) -> Result<String, Error>; fn get_return_url(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; + fn get_complete_authorize_url(&self) -> Result<String, Error>; } impl PaymentsPreProcessingData for types::PaymentsPreProcessingData { @@ -317,6 +318,11 @@ impl PaymentsPreProcessingData for types::PaymentsPreProcessingData { .clone() .ok_or_else(missing_field_err("browser_info")) } + fn get_complete_authorize_url(&self) -> Result<String, Error> { + self.complete_authorize_url + .clone() + .ok_or_else(missing_field_err("complete_authorize_url")) + } } pub trait PaymentsCaptureRequestData { @@ -592,6 +598,7 @@ pub trait PaymentsCompleteAuthorizeRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>; + fn get_complete_authorize_url(&self) -> Result<String, Error>; } impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { @@ -616,6 +623,11 @@ impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { .into(), ) } + fn get_complete_authorize_url(&self) -> Result<String, Error> { + self.complete_authorize_url + .clone() + .ok_or_else(missing_field_err("complete_authorize_url")) + } } pub trait PaymentsSyncRequestData { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ff4934e1efc..21cdec92ccb 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1489,6 +1489,22 @@ where router_data = router_data.preprocessing_steps(state, connector).await?; (router_data, false) + } else if connector.connector_name == router_types::Connector::Cybersource + && is_operation_complete_authorize(&operation) + && router_data.auth_type == storage_enums::AuthenticationType::ThreeDs + { + router_data = router_data.preprocessing_steps(state, connector).await?; + + // Should continue the flow only if no redirection_data is returned else a response with redirection form shall be returned + let should_continue = matches!( + router_data.response, + Ok(router_types::PaymentsResponseData::TransactionResponse { + redirection_data: None, + .. + }) + ) && router_data.status + != common_enums::AttemptStatus::AuthenticationFailed; + (router_data, should_continue) } else { (router_data, should_continue_payment) } @@ -2106,6 +2122,10 @@ pub fn is_operation_confirm<Op: Debug>(operation: &Op) -> bool { matches!(format!("{operation:?}").as_str(), "PaymentConfirm") } +pub fn is_operation_complete_authorize<Op: Debug>(operation: &Op) -> bool { + matches!(format!("{operation:?}").as_str(), "CompleteAuthorize") +} + #[cfg(feature = "olap")] pub async fn list_payments( state: AppState, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 27ddd3f6d81..6dd692f1525 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -154,7 +154,6 @@ default_imp_for_complete_authorize!( connector::Checkout, connector::Coinbase, connector::Cryptopay, - connector::Cybersource, connector::Dlocal, connector::Fiserv, connector::Forte, @@ -873,7 +872,6 @@ default_imp_for_pre_processing_steps!( connector::Checkout, connector::Coinbase, connector::Cryptopay, - connector::Cybersource, connector::Dlocal, connector::Iatapay, connector::Fiserv, diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index c934c7c2cd6..07af15a336d 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -412,6 +412,7 @@ impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentsPreProcessingData browser_info: data.browser_info, surcharge_details: data.surcharge_details, connector_transaction_id: None, + redirect_response: None, }) } } @@ -431,10 +432,11 @@ impl TryFrom<types::CompleteAuthorizeData> for types::PaymentsPreProcessingData order_details: None, router_return_url: None, webhook_url: None, - complete_authorize_url: None, + complete_authorize_url: data.complete_authorize_url, browser_info: data.browser_info, surcharge_details: None, connector_transaction_id: data.connector_transaction_id, + redirect_response: data.redirect_response, }) } } diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs index 2d52a145fea..68d0ee8d475 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -203,10 +203,19 @@ pub async fn complete_authorize_preprocessing_steps<F: Clone>( ], ); + let mut router_data_request = router_data.request.to_owned(); + + if let Ok(types::PaymentsResponseData::TransactionResponse { + connector_metadata, .. + }) = &resp.response + { + router_data_request.connector_meta = connector_metadata.to_owned(); + }; + let authorize_router_data = payments::helpers::router_data_type_conversion::<_, F, _, _, _, _>( resp.clone(), - router_data.request.to_owned(), + router_data_request, resp.response, ); diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 5a3a322fb14..dffcff23595 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1425,6 +1425,9 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; + let router_base_url = &additional_data.router_base_url; + let connector_name = &additional_data.connector_name; + let attempt = &payment_data.payment_attempt; let browser_info: Option<types::BrowserInformation> = payment_data .payment_attempt .browser_info @@ -1446,7 +1449,11 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz .as_ref() .map(|surcharge_details| surcharge_details.final_amount) .unwrap_or(payment_data.amount.into()); - + let complete_authorize_url = Some(helpers::create_complete_authorize_url( + router_base_url, + attempt, + connector_name, + )); Ok(Self { setup_future_usage: payment_data.payment_intent.setup_future_usage, mandate_id: payment_data.mandate_id.clone(), @@ -1463,6 +1470,8 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz connector_transaction_id: payment_data.payment_attempt.connector_transaction_id, redirect_response, connector_meta: payment_data.payment_attempt.connector_metadata, + complete_authorize_url, + metadata: payment_data.payment_intent.metadata, }) } } @@ -1541,6 +1550,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce browser_info, surcharge_details: payment_data.surcharge_details, connector_transaction_id: payment_data.payment_attempt.connector_transaction_id, + redirect_response: None, }) } } diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index fdaaa87bf40..9eb06d675a0 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -789,6 +789,15 @@ pub enum RedirectForm { BlueSnap { payment_fields_token: String, // payment-field-token }, + CybersourceAuthSetup { + access_token: String, + ddc_url: String, + reference_id: String, + }, + CybersourceConsumerAuth { + access_token: String, + step_up_url: String, + }, Payme, Braintree { client_token: String, @@ -1426,6 +1435,105 @@ pub fn build_redirection_form( "))) }} } + RedirectForm::CybersourceAuthSetup { + access_token, + ddc_url, + reference_id, + } => { + maud::html! { + (maud::DOCTYPE) + html { + head { + meta name="viewport" content="width=device-width, initial-scale=1"; + } + body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { + + div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } + + (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) + + (PreEscaped(r#" + <script> + var anime = bodymovin.loadAnimation({ + container: document.getElementById('loader1'), + renderer: 'svg', + loop: true, + autoplay: true, + name: 'hyperswitch loader', + animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} + }) + </script> + "#)) + + + h3 style="text-align: center;" { "Please wait while we process your payment..." } + } + + (PreEscaped(r#"<iframe id="cardinal_collection_iframe" name="collectionIframe" height="10" width="10" style="display: none;"></iframe>"#)) + (PreEscaped(format!("<form id=\"cardinal_collection_form\" method=\"POST\" target=\"collectionIframe\" action=\"{ddc_url}\"> + <input id=\"cardinal_collection_form_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> + </form>"))) + (PreEscaped(r#"<script> + window.onload = function() { + var cardinalCollectionForm = document.querySelector('#cardinal_collection_form'); if(cardinalCollectionForm) cardinalCollectionForm.submit(); + } + </script>"#)) + (PreEscaped(format!("<script> + window.addEventListener(\"message\", function(event) {{ + if (event.origin === \"https://centinelapistag.cardinalcommerce.com\" || event.origin === \"https://centinelapi.cardinalcommerce.com\") {{ + window.location.href = window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/cybersource?referenceId={reference_id}\"); + }} + }}, false); + </script> + "))) + }} + } + RedirectForm::CybersourceConsumerAuth { + access_token, + step_up_url, + } => { + maud::html! { + (maud::DOCTYPE) + html { + head { + meta name="viewport" content="width=device-width, initial-scale=1"; + } + body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { + + div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } + + (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) + + (PreEscaped(r#" + <script> + var anime = bodymovin.loadAnimation({ + container: document.getElementById('loader1'), + renderer: 'svg', + loop: true, + autoplay: true, + name: 'hyperswitch loader', + animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} + }) + </script> + "#)) + + + h3 style="text-align: center;" { "Please wait while we process your payment..." } + } + + // This is the iframe recommended by cybersource but the redirection happens inside this iframe once otp + // is received and we lose control of the redirection on user client browser, so to avoid that we have removed this iframe and directly consumed it. + // (PreEscaped(r#"<iframe id="step_up_iframe" style="border: none; margin-left: auto; margin-right: auto; display: block" height="800px" width="400px" name="stepUpIframe"></iframe>"#)) + (PreEscaped(format!("<form id=\"step_up_form\" method=\"POST\" action=\"{step_up_url}\"> + <input id=\"step_up_form_jwt_input\" type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> + </form>"))) + (PreEscaped(r#"<script> + window.onload = function() { + var stepUpForm = document.querySelector('#step_up_form'); if(stepUpForm) stepUpForm.submit(); + } + </script>"#)) + }} + } RedirectForm::Payme => { maud::html! { (maud::DOCTYPE) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 7cd45a0192f..3521a82a5a8 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -490,6 +490,7 @@ pub struct PaymentsPreProcessingData { pub surcharge_details: Option<types::SurchargeDetails>, pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, + pub redirect_response: Option<CompleteAuthorizeRedirectResponse>, } #[derive(Debug, Clone)] @@ -510,6 +511,8 @@ pub struct CompleteAuthorizeData { pub browser_info: Option<BrowserInformation>, pub connector_transaction_id: Option<String>, pub connector_meta: Option<serde_json::Value>, + pub complete_authorize_url: Option<String>, + pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Clone)]
2024-01-09T07:42:45Z
## Description <!-- Describe your changes in detail --> Implement 3DS flow for cards ``` Legend: UB: User Browser M: Merchant HS: Hyperswitch CS: Cybersource ``` ![Cybersource_3DS](https://github.com/juspay/hyperswitch/assets/55536657/eea4b266-970b-4f73-84c2-d19ca05a6ea2) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #3296 # ### QA Testing - Test Non-3DS flows to confirm they are not affected - Test 3DS transactions - Test mandates + 3DS transaction (zero and non-zero) All the possible 3DS test cases and test cards are available here: https://developer.cybersource.com/content/dam/docs/cybs/en-us/payer-authentication/developer/all/rest/payer-auth.pdf
af43b07e4394458db478bc16e5fb8d3b0d636a31
<img width="1139" alt="Screenshot 2024-01-09 at 6 23 43 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/e6f5c024-2116-4946-ae67-802e1fc4a126"> <img width="1138" alt="Screenshot 2024-01-09 at 6 23 51 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/9db71df7-a0b4-4c85-b611-1eba611e1ab9"> <img width="934" alt="Screenshot 2024-01-09 at 6 23 56 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/1a37edcb-c0e9-4c94-890e-e1f55fbc1971"> <img width="1151" alt="Screenshot 2024-01-09 at 6 24 15 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/cf4dc934-097e-4080-96da-fd3689d57b06"> ### QA Testing - Test Non-3DS flows to confirm they are not affected - Test 3DS transactions - Test mandates + 3DS transaction (zero and non-zero) All the possible 3DS test cases and test cards are available here: https://developer.cybersource.com/content/dam/docs/cybs/en-us/payer-authentication/developer/all/rest/payer-auth.pdf
[ "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/router/src/connector/cybersource.rs", "crates/router/src/connector/cybersource/transformers.rs", "crates/router/src/connector/utils.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments...
juspay/hyperswitch
juspay__hyperswitch-3293
Bug: feat: List merchant id and merchant name
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index d666dfc3bfa..07909a35782 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -1,4 +1,4 @@ -use common_utils::pii; +use common_utils::{crypto::OptionalEncryptableName, pii}; use masking::Secret; use crate::user_role::UserStatus; @@ -133,3 +133,9 @@ pub type VerifyEmailResponse = DashboardEntryResponse; pub struct SendVerifyEmailRequest { pub email: pii::Email, } + +#[derive(Debug, serde::Serialize)] +pub struct UserMerchantAccount { + pub merchant_id: String, + pub merchant_name: OptionalEncryptableName, +} diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 6fb76bd75b3..532f8208ecf 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -640,9 +640,23 @@ pub async fn create_merchant_account( pub async fn list_merchant_ids_for_user( state: AppState, user: auth::UserFromToken, -) -> UserResponse<Vec<String>> { +) -> UserResponse<Vec<user_api::UserMerchantAccount>> { + let merchant_ids = utils::user_role::get_merchant_ids_for_user(&state, &user.user_id).await?; + + let merchant_accounts = state + .store + .list_multiple_merchant_accounts(merchant_ids) + .await + .change_context(UserErrors::InternalServerError)?; + Ok(ApplicationResponse::Json( - utils::user_role::get_merchant_ids_for_user(state, &user.user_id).await?, + merchant_accounts + .into_iter() + .map(|acc| user_api::UserMerchantAccount { + merchant_id: acc.merchant_id, + merchant_name: acc.merchant_name, + }) + .collect(), )) } diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 4449338402f..c474a82981b 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -18,7 +18,7 @@ pub fn is_internal_role(role_id: &str) -> bool { || role_id == consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER } -pub async fn get_merchant_ids_for_user(state: AppState, user_id: &str) -> UserResult<Vec<String>> { +pub async fn get_merchant_ids_for_user(state: &AppState, user_id: &str) -> UserResult<Vec<String>> { Ok(state .store .list_user_roles_by_user_id(user_id)
2024-01-09T07:39:44Z
## Description Added Merchant name is list merchant api. <!-- Describe your changes in detail --> ## Motivation and Context Dashboard needs to show merchant name is available. <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
ecf51b5e3a30f055634edfafcd36f64cef535a53
``` curl --location --request GET '<URL>/user/switch/list' \ --header 'Authorization: Bearer <JWT>' ``` Above api should return list of merchant accounts the user (whos jwt is being used) has access to. ``` [ { "merchant_id": "merchant_1704706726", "merchant_name": null }, { "merchant_id": "merchant_1704706837", "merchant_name": "some merchant name" } ] ```
[ "crates/api_models/src/user.rs", "crates/router/src/core/user.rs", "crates/router/src/utils/user_role.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3260
Bug: [BUG] WASM build fails on latest pull ### Bug Description The workspace builds ok, but wasm-pack build `wasm-pack build --target web --out-dir "${PWD}/wasm" --out-name euclid crates/euclid_wasm -- --features development,dummy_connector` fails on compilation of mio-0.8.8 ### Expected Behavior build wasm folder correctly ### Actual Behavior Compilation error on mio-0.8.8: ``` [INFO]: 🎯 Checking for the Wasm target... [INFO]: 🌀 Compiling to Wasm... Compiling proc-macro2 v1.0.76 Compiling serde v1.0.195 Compiling once_cell v1.19.0 Compiling memchr v2.7.1 Compiling quote v1.0.35 Compiling syn v2.0.48 Compiling syn v1.0.109 Compiling serde_derive v1.0.195 Compiling itoa v1.0.10 Compiling wasm-bindgen-shared v0.2.89 Compiling futures-core v0.3.30 Compiling wasm-bindgen-backend v0.2.89 Compiling thiserror v1.0.56 Compiling wasm-bindgen-macro-support v0.2.89 Compiling wasm-bindgen v0.2.89 Compiling wasm-bindgen-macro v0.2.89 Compiling thiserror-impl v1.0.56 Compiling smallvec v1.11.2 Compiling futures-sink v0.3.30 Compiling js-sys v0.3.66 Compiling lock_api v0.4.11 Compiling parking_lot_core v0.9.9 Compiling tracing-core v0.1.32 Compiling serde_json v1.0.111 Compiling parking_lot v0.12.1 Compiling futures-channel v0.3.30 Compiling mio v0.8.10 error[E0432]: unresolved import `crate::sys::IoSourceState` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:12:5 | 12 | use crate::sys::IoSourceState; | ^^^^^^^^^^^^^^^^^^^^^^^^^ no `IoSourceState` in `sys` error[E0432]: unresolved import `crate::sys::tcp` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:15:17 | 15 | use crate::sys::tcp::{bind, listen, new_for_addr}; | ^^^ could not find `tcp` in `sys` error[E0432]: unresolved import `crate::sys::tcp` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:13:17 | 13 | use crate::sys::tcp::{connect, new_for_addr}; | ^^^ could not find `tcp` in `sys` error[E0433]: failed to resolve: could not find `Selector` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/poll.rs:312:18 | 312 | sys::Selector::new().map(|selector| Poll { | ^^^^^^^^ could not find `Selector` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:24:14 | 24 | sys::event::token(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:38:14 | 38 | sys::event::is_readable(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:43:14 | 43 | sys::event::is_writable(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:68:14 | 68 | sys::event::is_error(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:99:14 | 99 | sys::event::is_read_closed(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:129:14 | 129 | sys::event::is_write_closed(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:151:14 | 151 | sys::event::is_priority(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:173:14 | 173 | sys::event::is_aio(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:183:14 | 183 | sys::event::is_lio(&self.inner) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `event` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:221:26 | 221 | sys::event::debug_details(f, self.0) | ^^^^^ could not find `event` in `sys` error[E0433]: failed to resolve: could not find `tcp` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:103:18 | 103 | sys::tcp::accept(inner).map(|(stream, addr)| (TcpStream::from_std(stream), addr)) | ^^^ could not find `tcp` in `sys` error[E0433]: failed to resolve: could not find `udp` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:122:14 | 122 | sys::udp::bind(addr).map(UdpSocket::from_std) | ^^^ could not find `udp` in `sys` error[E0433]: failed to resolve: could not find `udp` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:544:14 | 544 | sys::udp::only_v6(&self.inner) | ^^^ could not find `udp` in `sys` error[E0412]: cannot find type `Selector` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/poll.rs:263:20 | 263 | selector: sys::Selector, | ^^^^^^^^ not found in `sys` error[E0412]: cannot find type `Selector` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/poll.rs:710:44 | 710 | pub(crate) fn selector(&self) -> &sys::Selector { | ^^^^^^^^ not found in `sys` error[E0412]: cannot find type `Waker` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/waker.rs:79:17 | 79 | inner: sys::Waker, | ^^^^^ not found in `sys` | help: consider importing one of these items | 1 + use core::task::Waker; | 1 + use crate::Waker; | 1 + use std::task::Waker; | help: if you import `Waker`, refer to it directly | 79 - inner: sys::Waker, 79 + inner: Waker, | error[E0433]: failed to resolve: could not find `Waker` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/waker.rs:87:14 | 87 | sys::Waker::new(registry.selector(), token).map(|inner| Waker { inner }) | ^^^^^ could not find `Waker` in `sys` | help: consider importing one of these items | 1 + use core::task::Waker; | 1 + use crate::Waker; | 1 + use std::task::Waker; | help: if you import `Waker`, refer to it directly | 87 - sys::Waker::new(registry.selector(), token).map(|inner| Waker { inner }) 87 + Waker::new(registry.selector(), token).map(|inner| Waker { inner }) | error[E0412]: cannot find type `Event` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:18:17 | 18 | inner: sys::Event, | ^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::event::Event; | help: if you import `Event`, refer to it directly | 18 - inner: sys::Event, 18 + inner: Event, | error[E0412]: cannot find type `Event` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:187:55 | 187 | pub(crate) fn from_sys_event_ref(sys_event: &sys::Event) -> &Event { | ^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::event::Event; | help: if you import `Event`, refer to it directly | 187 - pub(crate) fn from_sys_event_ref(sys_event: &sys::Event) -> &Event { 187 + pub(crate) fn from_sys_event_ref(sys_event: &Event) -> &Event { | error[E0412]: cannot find type `Event` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:191:41 | 191 | &*(sys_event as *const sys::Event as *const Event) | ^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::event::Event; | help: if you import `Event`, refer to it directly | 191 - &*(sys_event as *const sys::Event as *const Event) 191 + &*(sys_event as *const Event as *const Event) | error[E0412]: cannot find type `Event` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/event.rs:217:46 | 217 | struct EventDetails<'a>(&'a sys::Event); | ^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::event::Event; | help: if you import `Event`, refer to it directly | 217 - struct EventDetails<'a>(&'a sys::Event); 217 + struct EventDetails<'a>(&'a Event); | error[E0412]: cannot find type `Events` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/events.rs:43:17 | 43 | inner: sys::Events, | ^^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::Events; | help: if you import `Events`, refer to it directly | 43 - inner: sys::Events, 43 + inner: Events, | error[E0433]: failed to resolve: could not find `Events` in `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/events.rs:94:25 | 94 | inner: sys::Events::with_capacity(capacity), | ^^^^^^ could not find `Events` in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::Events; | help: if you import `Events`, refer to it directly | 94 - inner: sys::Events::with_capacity(capacity), 94 + inner: Events::with_capacity(capacity), | error[E0412]: cannot find type `Events` in module `sys` --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/events.rs:189:47 | 189 | pub(crate) fn sys(&mut self) -> &mut sys::Events { | ^^^^^^ not found in `sys` | help: consider importing this struct through its public re-export | 1 + use crate::Events; | help: if you import `Events`, refer to it directly | 189 - pub(crate) fn sys(&mut self) -> &mut sys::Events { 189 + pub(crate) fn sys(&mut self) -> &mut Events { | error[E0425]: cannot find value `listener` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:74:24 | 74 | set_reuseaddr(&listener.inner, true)?; | ^^^^^^^^ not found in this scope error[E0425]: cannot find value `listener` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:76:15 | 76 | bind(&listener.inner, addr)?; | ^^^^^^^^ not found in this scope error[E0425]: cannot find value `listener` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:77:17 | 77 | listen(&listener.inner, 1024)?; | ^^^^^^^^ not found in this scope error[E0425]: cannot find value `listener` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:78:12 | 78 | Ok(listener) | ^^^^^^^^ not found in this scope error[E0425]: cannot find value `stream` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:90:18 | 90 | connect(&stream.inner, addr)?; | ^^^^^^ not found in this scope error[E0425]: cannot find value `stream` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:91:12 | 91 | Ok(stream) | ^^^^^^ not found in this scope error[E0425]: cannot find function `set_reuseaddr` in this scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:74:9 | 74 | set_reuseaddr(&listener.inner, true)?; | ^^^^^^^^^^^^^ not found in this scope error[E0599]: no method named `register` found for struct `IoSource<std::net::TcpListener>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:146:20 | 146 | self.inner.register(registry, token, interests) | ^^^^^^^^ method not found in `IoSource<TcpListener>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `register` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `register`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `reregister` found for struct `IoSource<std::net::TcpListener>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:155:20 | 155 | self.inner.reregister(registry, token, interests) | ^^^^^^^^^^ method not found in `IoSource<TcpListener>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `reregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `reregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `deregister` found for struct `IoSource<std::net::TcpListener>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/listener.rs:159:20 | 159 | self.inner.deregister(registry) | ^^^^^^^^^^ method not found in `IoSource<TcpListener>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `deregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `deregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `register` found for struct `IoSource<std::net::TcpStream>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:325:20 | 325 | self.inner.register(registry, token, interests) | ^^^^^^^^ method not found in `IoSource<TcpStream>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `register` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `register`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `reregister` found for struct `IoSource<std::net::TcpStream>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:334:20 | 334 | self.inner.reregister(registry, token, interests) | ^^^^^^^^^^ method not found in `IoSource<TcpStream>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `reregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `reregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `deregister` found for struct `IoSource<std::net::TcpStream>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/tcp/stream.rs:338:20 | 338 | self.inner.deregister(registry) | ^^^^^^^^^^ method not found in `IoSource<TcpStream>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `deregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `deregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `register` found for struct `IoSource<std::net::UdpSocket>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:622:20 | 622 | self.inner.register(registry, token, interests) | ^^^^^^^^ method not found in `IoSource<UdpSocket>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `register` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `register`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `reregister` found for struct `IoSource<std::net::UdpSocket>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:631:20 | 631 | self.inner.reregister(registry, token, interests) | ^^^^^^^^^^ method not found in `IoSource<UdpSocket>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `reregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `reregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ error[E0599]: no method named `deregister` found for struct `IoSource<std::net::UdpSocket>` in the current scope --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/net/udp.rs:635:20 | 635 | self.inner.deregister(registry) | ^^^^^^^^^^ method not found in `IoSource<UdpSocket>` | ::: /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/io_source.rs:62:1 | 62 | pub struct IoSource<T> { | ---------------------- method `deregister` not found for this struct | = help: items from traits can only be used if the trait is implemented and in scope note: `Source` defines an item `deregister`, perhaps you need to implement it --> /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/mio-0.8.10/src/event/source.rs:75:1 | 75 | pub trait Source { | ^^^^^^^^^^^^^^^^ Some errors have detailed explanations: E0412, E0425, E0432, E0433, E0599. For more information about an error, try `rustc --explain E0412`. error: could not compile `mio` (lib) due to 44 previous errors warning: build failed, waiting for other jobs to finish... Error: Compiling your crate to WebAssembly failed Caused by: Compiling your crate to WebAssembly failed Caused by: failed to execute `cargo build`: exited with exit status: 101 full command: cd "crates/euclid_wasm" && "cargo" "build" "--lib" "--release" "--target" "wasm32-unknown-unknown" "--features" "development,dummy_connector" ``` ### Steps To Reproduce wasm-pack build --target web --out-dir "${PWD}/wasm" --out-name euclid crates/euclid_wasm -- --features development,dummy_connector ### Context For The Bug _No response_ ### Environment Self-hosted sandbox 1. Operating system: Ubuntu 22.04 2. Rust version (output of `rustc --version`): `1.75` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/cards/Cargo.toml b/crates/cards/Cargo.toml index cf3e25459c6..6892350ce6f 100644 --- a/crates/cards/Cargo.toml +++ b/crates/cards/Cargo.toml @@ -19,6 +19,8 @@ time = "0.3.21" # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } masking = { version = "0.1.0", path = "../masking" } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } [dev-dependencies] diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index 001eab3004d..ca47c73c7c2 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -1,6 +1,7 @@ use std::{fmt, ops::Deref, str::FromStr}; use masking::{PeekInterface, Strategy, StrongSecret, WithType}; +#[cfg(not(target_arch = "wasm32"))] use router_env::logger; use serde::{Deserialize, Deserializer, Serialize}; use thiserror::Error; @@ -89,6 +90,7 @@ where if let Some(value) = val_str.get(..6) { write!(f, "{}{}", value, "*".repeat(val_str.len() - 6)) } else { + #[cfg(not(target_arch = "wasm32"))] logger::error!("Invalid card number {val_str}"); WithType::fmt(val, f) }
2024-01-08T17:33:58Z
## Description <!-- Describe your changes in detail --> This PR fixes failing `wasm-pack build` for the `euclid_wasm` crate. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #3260. #
5484cf42426d37667266fb952b800a6dab5e305e
<img width="1242" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3d7203ad-c50d-428e-9ec9-d05248c398bd">
[ "crates/cards/Cargo.toml", "crates/cards/src/validate.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3282
Bug: [BUG] [BOA/CYBERSOURCE] merchant_defined_information giving authentication error ### Bug Description Some payments fail when `merchant_defined_information` is passed for each payment with data coming from merchant in payment requests metadata. ### Expected Behavior All payments should succeed when `merchant_defined_information` is passed for each payment with data coming from merchant in payment requests metadata. ### Actual Behavior Some payments fail when `merchant_defined_information` is passed for each payment with data coming from merchant in payment requests metadata. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug Due to hashmap being used to populate key,value pairs in merchantDefinedInformation the order in which the (key,value) pairs gets inserted into merchantDefinedInformation is not fixed. Due to which for some payments there is a mismatch between the body used in generation of signature(in payments headers) and the body passed in the actual request. This mismatch causes the connector to throw authentication error for some payments. ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index def93ec5f83..aa47efbe714 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1,5 +1,3 @@ -use std::collections::HashMap; - use api_models::payments; use base64::Engine; use common_utils::pii; @@ -323,8 +321,9 @@ impl From<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> { fn foreign_from(metadata: Value) -> Self { - let hashmap: HashMap<String, Value> = - serde_json::from_str(&metadata.to_string()).unwrap_or(HashMap::new()); + let hashmap: std::collections::BTreeMap<String, Value> = + serde_json::from_str(&metadata.to_string()) + .unwrap_or(std::collections::BTreeMap::new()); let mut vector: Self = Self::new(); let mut iter = 1; for (key, value) in hashmap { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index cf769f1a2fd..e6034f7af7f 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1,5 +1,3 @@ -use std::collections::HashMap; - use api_models::payments; use base64::Engine; use common_utils::pii; @@ -543,8 +541,9 @@ fn build_bill_to( impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> { fn foreign_from(metadata: Value) -> Self { - let hashmap: HashMap<String, Value> = - serde_json::from_str(&metadata.to_string()).unwrap_or(HashMap::new()); + let hashmap: std::collections::BTreeMap<String, Value> = + serde_json::from_str(&metadata.to_string()) + .unwrap_or(std::collections::BTreeMap::new()); let mut vector: Self = Self::new(); let mut iter = 1; for (key, value) in hashmap {
2024-01-08T17:01:35Z
## Description <!-- Describe your changes in detail --> Some payments fail when merchant_defined_information is passed for the payment with data coming from merchant in payment requests metadata. This was happening because hashmaps were being used to populate key,value pairs in merchantDefinedInformation due to which the order in which the (key,value) pairs gets inserted into merchantDefinedInformation was not fixed. Due to this for some payments there was a mismatch between the body used in generation of signature(for payments headers) and the body which was being passed in the actual request. This mismatch caused the connector to throw authentication error for those payments. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3282 #
5484cf42426d37667266fb952b800a6dab5e305e
Testing can be done by creating a card/gpay/applepay payment and by passing the following metadata in PAYMENTS-CREATE: `"metadata": { "count_tickets": 1, "transaction_number": "5590043" }` You should then be able to see the metadata on BOA dashboard for that payment: ![292885857-2693f174-0552-45a9-af42-6606e874231f](https://github.com/juspay/hyperswitch/assets/41580413/442f415a-b788-485a-88ad-9bf71dc934ba)
[ "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cybersource/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3272
Bug: [FEATURE] [BOA/Cybersource] Store AVS Response in connector metadata ### Feature Description The AVS fields in payments response for authorize flow should be stored in connector metadata. ### Possible Implementation The AVS fields in payments response for authorize flow should be stored in connector metadata. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/router/src/connector/bankofamerica.rs index 1e0856a9ccc..aeb3dafcfa2 100644 --- a/crates/router/src/connector/bankofamerica.rs +++ b/crates/router/src/connector/bankofamerica.rs @@ -205,7 +205,7 @@ impl ConnectorCommon for Bankofamerica { }; match response { transformers::BankOfAmericaErrorResponse::StandardError(response) => { - let (code, message) = match response.error_information { + let (code, connector_reason) = match response.error_information { Some(ref error_info) => (error_info.reason.clone(), error_info.message.clone()), None => ( response @@ -218,13 +218,13 @@ impl ConnectorCommon for Bankofamerica { .map_or(error_message.to_string(), |message| message), ), }; - let connector_reason = match response.details { + let message = match response.details { Some(details) => details .iter() .map(|det| format!("{} : {}", det.field, det.reason)) .collect::<Vec<_>>() .join(", "), - None => message.clone(), + None => connector_reason.clone(), }; Ok(ErrorResponse { diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index e024eb7a501..6abe1b634df 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -343,6 +343,30 @@ pub struct ClientReferenceInformation { code: Option<String>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientProcessorInformation { + avs: Option<Avs>, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientRiskInformation { + rules: Option<Vec<ClientRiskInformationRules>>, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ClientRiskInformationRules { + name: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Avs { + code: String, + code_raw: String, +} + impl TryFrom<( &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>, @@ -658,10 +682,12 @@ pub struct BankOfAmericaClientReferenceResponse { id: String, status: BankofamericaPaymentStatus, client_reference_information: ClientReferenceInformation, + processor_information: Option<ClientProcessorInformation>, + risk_information: Option<ClientRiskInformation>, error_information: Option<BankOfAmericaErrorInformation>, } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaErrorInformationResponse { id: String, @@ -674,6 +700,55 @@ pub struct BankOfAmericaErrorInformation { message: Option<String>, } +impl<F, T> + From<( + &BankOfAmericaErrorInformationResponse, + types::ResponseRouterData<F, BankOfAmericaPaymentsResponse, T, types::PaymentsResponseData>, + Option<enums::AttemptStatus>, + )> for types::RouterData<F, T, types::PaymentsResponseData> +{ + fn from( + (error_response, item, transaction_status): ( + &BankOfAmericaErrorInformationResponse, + types::ResponseRouterData< + F, + BankOfAmericaPaymentsResponse, + T, + types::PaymentsResponseData, + >, + Option<enums::AttemptStatus>, + ), + ) -> Self { + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + match transaction_status { + Some(status) => Self { + response, + status, + ..item.data + }, + None => Self { + response, + ..item.data + }, + } + } +} + fn get_error_response_if_failure( (info_response, status, http_code): ( &BankOfAmericaClientReferenceResponse, @@ -684,6 +759,7 @@ fn get_error_response_if_failure( if utils::is_payment_failure(status) { Some(types::ErrorResponse::from(( &info_response.error_information, + &info_response.risk_information, http_code, info_response.id.clone(), ))) @@ -706,7 +782,10 @@ fn get_payment_response( resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: None, mandate_reference: None, - connector_metadata: None, + connector_metadata: info_response + .processor_information + .as_ref() + .map(|processor_information| serde_json::json!({"avs_response": processor_information.avs})), network_txn_id: None, connector_response_reference_id: Some( info_response @@ -752,26 +831,13 @@ impl<F> ..item.data }) } - BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id), - }) - }, - status: enums::AttemptStatus::Failure, - ..item.data - }), + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))) + } } } } @@ -806,24 +872,9 @@ impl<F> ..item.data }) } - BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id), - }) - }, - ..item.data - }), + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from((&error_response.clone(), item, None))) + } } } } @@ -858,24 +909,9 @@ impl<F> ..item.data }) } - BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id), - }) - }, - ..item.data - }), + BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => { + Ok(Self::from((&error_response.clone(), item, None))) + } } } } @@ -927,10 +963,12 @@ impl<F> app_response.application_information.status, item.data.request.is_auto_capture()?, )); + let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { Ok(Self { response: Err(types::ErrorResponse::from(( &app_response.error_information, + &risk_info, item.http_code, app_response.id.clone(), ))), @@ -1213,8 +1251,8 @@ pub struct BankOfAmericaAuthenticationErrorResponse { #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum BankOfAmericaErrorResponse { - StandardError(BankOfAmericaStandardErrorResponse), AuthenticationError(BankOfAmericaAuthenticationErrorResponse), + StandardError(BankOfAmericaStandardErrorResponse), } #[derive(Debug, Deserialize, Clone)] @@ -1235,29 +1273,53 @@ pub struct AuthenticationErrorInformation { pub rmsg: String, } -impl From<(&Option<BankOfAmericaErrorInformation>, u16, String)> for types::ErrorResponse { +impl + From<( + &Option<BankOfAmericaErrorInformation>, + &Option<ClientRiskInformation>, + u16, + String, + )> for types::ErrorResponse +{ fn from( - (error_data, status_code, transaction_id): ( + (error_data, risk_information, status_code, transaction_id): ( &Option<BankOfAmericaErrorInformation>, + &Option<ClientRiskInformation>, u16, String, ), ) -> Self { - let error_message = error_data + let avs_message = risk_information .clone() - .and_then(|error_details| error_details.message); + .map(|client_risk_information| { + client_risk_information.rules.map(|rules| { + rules + .iter() + .map(|risk_info| format!(" , {}", risk_info.name)) + .collect::<Vec<String>>() + .join("") + }) + }) + .unwrap_or(Some("".to_string())); let error_reason = error_data + .clone() + .map(|error_details| { + error_details.message.unwrap_or("".to_string()) + + &avs_message.unwrap_or("".to_string()) + }) + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_data .clone() .and_then(|error_details| error_details.reason); Self { - code: error_reason + code: error_message .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason + message: error_message .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_message.clone(), + reason: Some(error_reason.clone()), status_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(transaction_id.clone()), diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 33503102e4b..6c4ea4c61fe 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -124,7 +124,7 @@ impl ConnectorCommon for Cybersource { }; match response { transformers::CybersourceErrorResponse::StandardError(response) => { - let (code, message) = match response.error_information { + let (code, connector_reason) = match response.error_information { Some(ref error_info) => (error_info.reason.clone(), error_info.message.clone()), None => ( response @@ -137,13 +137,13 @@ impl ConnectorCommon for Cybersource { .map_or(error_message.to_string(), |message| message), ), }; - let connector_reason = match response.details { + let message = match response.details { Some(details) => details .iter() .map(|det| format!("{} : {}", det.field, det.reason)) .collect::<Vec<_>>() .join(", "), - None => message.clone(), + None => connector_reason.clone(), }; Ok(types::ErrorResponse { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index bc69fb78129..8ae2ce29e5b 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1105,6 +1105,8 @@ pub struct CybersourceClientReferenceResponse { id: String, status: CybersourcePaymentStatus, client_reference_information: ClientReferenceInformation, + processor_information: Option<ClientProcessorInformation>, + risk_information: Option<ClientRiskInformation>, token_information: Option<CybersourceTokenInformation>, error_information: Option<CybersourceErrorInformation>, } @@ -1136,6 +1138,30 @@ pub struct ClientReferenceInformation { code: Option<String>, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientProcessorInformation { + avs: Option<Avs>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Avs { + code: String, + code_raw: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientRiskInformation { + rules: Option<Vec<ClientRiskInformationRules>>, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct ClientRiskInformationRules { + name: String, +} + #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceTokenInformation { @@ -1152,10 +1178,11 @@ impl<F, T> From<( &CybersourceErrorInformationResponse, types::ResponseRouterData<F, CybersourcePaymentsResponse, T, types::PaymentsResponseData>, + Option<enums::AttemptStatus>, )> for types::RouterData<F, T, types::PaymentsResponseData> { fn from( - (error_response, item): ( + (error_response, item, transaction_status): ( &CybersourceErrorInformationResponse, types::ResponseRouterData< F, @@ -1163,25 +1190,35 @@ impl<F, T> T, types::PaymentsResponseData, >, + Option<enums::AttemptStatus>, ), ) -> Self { - Self { - response: { - let error_reason = &error_response.error_information.reason; - Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message.clone(), - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id.clone()), - }) + let error_reason = error_response + .error_information + .message + .to_owned() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_response.error_information.reason.to_owned(); + let response = Err(types::ErrorResponse { + code: error_message + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: Some(error_reason), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(error_response.id.clone()), + }); + match transaction_status { + Some(status) => Self { + response, + status, + ..item.data + }, + None => Self { + response, + ..item.data }, - ..item.data } } } @@ -1196,6 +1233,7 @@ fn get_error_response_if_failure( if utils::is_payment_failure(status) { Some(types::ErrorResponse::from(( &info_response.error_information, + &info_response.risk_information, http_code, info_response.id.clone(), ))) @@ -1229,7 +1267,10 @@ fn get_payment_response( resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), redirection_data: None, mandate_reference, - connector_metadata: None, + connector_metadata: info_response + .processor_information + .as_ref() + .map(|processor_information| serde_json::json!({"avs_response": processor_information.avs})), network_txn_id: None, connector_response_reference_id: Some( info_response @@ -1276,25 +1317,11 @@ impl<F> ..item.data }) } - CybersourcePaymentsResponse::ErrorInformation(error_response) => { - let error_reason = &error_response.error_information.reason; - Ok(Self { - response: Err(types::ErrorResponse { - code: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason - .clone() - .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_response.error_information.message, - status_code: item.http_code, - attempt_status: None, - connector_transaction_id: Some(error_response.id.clone()), - }), - status: enums::AttemptStatus::Failure, - ..item.data - }) - } + CybersourcePaymentsResponse::ErrorInformation(ref error_response) => Ok(Self::from(( + &error_response.clone(), + item, + Some(enums::AttemptStatus::Failure), + ))), } } } @@ -1330,7 +1357,7 @@ impl<F> }) } CybersourcePaymentsResponse::ErrorInformation(ref error_response) => { - Ok(Self::from((&error_response.clone(), item))) + Ok(Self::from((&error_response.clone(), item, None))) } } } @@ -1367,7 +1394,7 @@ impl<F> }) } CybersourcePaymentsResponse::ErrorInformation(ref error_response) => { - Ok(Self::from((&error_response.clone(), item))) + Ok(Self::from((&error_response.clone(), item, None))) } } } @@ -1556,10 +1583,12 @@ impl<F> )); let incremental_authorization_allowed = Some(status == enums::AttemptStatus::Authorized); + let risk_info: Option<ClientRiskInformation> = None; if utils::is_payment_failure(status) { Ok(Self { response: Err(types::ErrorResponse::from(( &app_response.error_information, + &risk_info, item.http_code, app_response.id.clone(), ))), @@ -1782,30 +1811,53 @@ pub struct AuthenticationErrorInformation { pub rmsg: String, } -impl From<(&Option<CybersourceErrorInformation>, u16, String)> for types::ErrorResponse { +impl + From<( + &Option<CybersourceErrorInformation>, + &Option<ClientRiskInformation>, + u16, + String, + )> for types::ErrorResponse +{ fn from( - (error_data, status_code, transaction_id): ( + (error_data, risk_information, status_code, transaction_id): ( &Option<CybersourceErrorInformation>, + &Option<ClientRiskInformation>, u16, String, ), ) -> Self { - let error_message = error_data + let avs_message = risk_information .clone() - .and_then(|error_details| error_details.message); - + .map(|client_risk_information| { + client_risk_information.rules.map(|rules| { + rules + .iter() + .map(|risk_info| format!(" , {}", risk_info.name)) + .collect::<Vec<String>>() + .join("") + }) + }) + .unwrap_or(Some("".to_string())); let error_reason = error_data + .clone() + .map(|error_details| { + error_details.message.unwrap_or("".to_string()) + + &avs_message.unwrap_or("".to_string()) + }) + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()); + let error_message = error_data .clone() .and_then(|error_details| error_details.reason); Self { - code: error_reason + code: error_message .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), - message: error_reason + message: error_message .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error_message.clone(), + reason: Some(error_reason.clone()), status_code, attempt_status: Some(enums::AttemptStatus::Failure), connector_transaction_id: Some(transaction_id.clone()),
2024-01-08T09:39:35Z
## Description <!-- Describe your changes in detail --> This PR contains the following changes for BOA/Cybersource: 1. The AVS response being sent by BOA/Cybersource for authorize flow is being stored in `connector_metadata` 2. In case of payments failing due to AVS check the failure reason will also contain the details of the AVS Check 3. In case of general failures the response message is used to populate our error reason and response details is used to populate our error message. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/3272 #
9eaebe8db3d83105ef1e8fc784241e1fb795dd22
1. Create a successful payment and verify that avs_response is stored in connector_metadata in db for the payment <img width="1073" alt="image" src="https://github.com/juspay/hyperswitch/assets/41580413/ceed3f94-523c-424a-be4d-32657b193416"> Curl for creating payment: ```curl curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: API_KEY_HERE' \ --data-raw '{ "amount": 1404, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "CustomerX", "email": "guest@example.com", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe", "card_cvc": "029" } }, "billing": { "address": { "line1": "cq", "city": "dshcvjhdw", "state": "whecvjkcdv", "zip": "46205", "country": "MW", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "12345", "country_code": "+93" } }, "metadata": { "count_tickets": 1, "transaction_number": "12321" }, "business_label": "food", "business_country": "US" }' ``` connector_response: ```json Ok(Ok(Response { headers: Some({"cache-control": "no-cache, no-store, must-revalidate", "pragma": "no-cache", "expires": "-1", "strict-transport-security": "max-age=31536000", "content-type": "application/hal+json", "content-length": "1621", "x-response-time": "1481ms", "x-opnet-transaction-trace": "HIDDEN", "connection": "keep-alive", "v-c-correlation-id": "HIDDEN"}), response: b"{\"_links\":{\"void\":{\"method\":\"POST\",\"href\":\"/pts/v2/payments/7049799548496957104951/voids\"},\"self\":{\"method\":\"GET\",\"href\":\"/pts/v2/payments/7049799548496957104951\"}},\"clientReferenceInformation\":{\"code\":\"pay_D0hUwTOaupjcu8P2qqcH_1\"},\"consumerAuthenticationInformation\":{\"token\":\"HIDDEN"},\"id\":\"7049799548496957104951\",\"orderInformation\":{\"amountDetails\":{\"totalAmount\":\"14.04\",\"authorizedAmount\":\"14.04\",\"currency\":\"USD\"}},\"paymentAccountInformation\":{\"card\":{\"type\":\"001\"}},\"paymentInformation\":{\"tokenizedCard\":{\"type\":\"001\"},\"scheme\":\"VISA DEBIT\",\"bin\":\"411111\",\"accountType\":\"Visa Classic\",\"issuer\":\"HIDDEN SP. Z O.O\",\"card\":{\"type\":\"001\"},\"binCountry\":\"PL\"},\"processorInformation\":{\"systemTraceAuditNumber\":\"HIDDEN\",\"approvalCode\":\"HIDDEN\",\"cardVerification\":{\"resultCodeRaw\":\"M\",\"resultCode\":\"M\"},\"merchantAdvice\":{\"code\":\"01\",\"codeRaw\":\"M001\"},\"responseDetails\":\"ABC\",\"networkTransactionId\":\"HIDDEN\",\"retrievalReferenceNumber\":\"HIDDEN\",\"consumerAuthenticationResponse\":{\"code\":\"2\",\"codeRaw\":\"2\"},\"transactionId\":\"HIDDEN\",\"responseCode\":\"00\",**\"avs\":{\"code\":\"Y\",\"codeRaw\":\"Y\"}},**\"reconciliationId\":\"HIDDEN\",\"riskInformation\":{\"localTime\":\"15:32:34\",\"score\":{\"result\":\"68\",\"factorCodes\":[\"B\"],\"modelUsed\":\"default_cemea\"},\"infoCodes\":{\"address\":[\"MM-BIN\",\"UNV-ADDR\"],\"identityChange\":[\"ID-X-HPOS\"]},\"profile\":{\"earlyDecision\":\"ACCEPT\",\"name\":\"Standard mid-market profile\",\"selectorRule\":\"Default Active Profile\"}},\"status\":\"AUTHORIZED\",\"submitTimeUtc\":\"2024-01-11T13:32:35Z\"}", status_code: 201 })) ``` 2. Testing can be done by creating a AVS mismatch error for a payment. You should see the following details in the error_message. (AVS Mismatch can be triggered by enabling Fraud Rules on BOA/Cybersource Dashboard) ```json { "payment_id": "pay_p6jsWMZ0Rdi2eZTasuTm", "merchant_id": "merchant_1704716850", "status": "failed", "amount": 1404, "net_amount": 1404, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_p6jsWMZ0Rdi2eZTasuTm_secret_7P0lx3N6COfGLvS4yBRl", "created": "2024-01-11T13:37:01.254Z", "currency": "USD", "customer_id": "CustomerX", "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_exp_month": "12", "card_exp_year": "30", "card_holder_name": "joseph Doe" } }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "dshcvjhdw", "country": "MW", "line1": "cq", "line2": null, "line3": null, "zip": "46205", "state": "whecvjkcdv", "first_name": "joseph", "last_name": "doe" }, "phone": { "number": "12345", "country_code": "+93" } }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": "DECISION_PROFILE_REJECT", "error_message": "The order has been rejected by Decision Manager , Fraud Score - Reject", "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": "cybersource_US_food_default", "business_country": "US", "business_label": "food", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "CustomerX", "created_at": 1704980221, "expires": 1704983821, "secret": "epk_83a362750bd34f1f85c1a3303905bf4b" }, "manual_retry_allowed": true, "connector_transaction_id": "7049802214936686604953", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590043" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_aLMwDWebJFLj05EIBPCm", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_x7psrN0rGR7OOaljMXC3", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null } ``` ![Screenshot 2024-01-11 at 7 07 40 PM](https://github.com/juspay/hyperswitch/assets/41580413/f43168ea-21db-4032-abb4-968884b20447) 3. To create a general failure pass line1 as empty string. You should see the following error_message. ![Screenshot 2024-01-08 at 7 55 02 PM](https://github.com/juspay/hyperswitch/assets/41580413/71342cc7-3d55-4b1c-9ce1-b23dd3765f89)
[ "crates/router/src/connector/bankofamerica.rs", "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cybersource.rs", "crates/router/src/connector/cybersource/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3263
Bug: [FEATURE] : [Connector] Implement Revoke Mandate Flow ### Feature Description When revoke-mandate endpoint is triggered, the mandate should be revoked with connector also. Currently it is being revoked only at core level which is a feature gap. ### Possible Implementation Add a `execute_connector_processing_step` and a flow to revoke the mandate at connector level ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs index 035f7adec9f..5c0810dc21b 100644 --- a/crates/api_models/src/mandates.rs +++ b/crates/api_models/src/mandates.rs @@ -17,6 +17,12 @@ pub struct MandateRevokedResponse { /// The status for mandates #[schema(value_type = MandateStatus)] pub status: api_enums::MandateStatus, + /// If there was an error while calling the connectors the code is received here + #[schema(example = "E0001")] + pub error_code: Option<String>, + /// If there was an error while calling the connector the error message is received here + #[schema(example = "Failed while verifying the card")] + pub error_message: Option<String>, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone)] diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 3496f2483ab..33503102e4b 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -55,6 +55,7 @@ impl Cybersource { } = auth; let is_post_method = matches!(http_method, services::Method::Post); let is_patch_method = matches!(http_method, services::Method::Patch); + let is_delete_method = matches!(http_method, services::Method::Delete); let digest_str = if is_post_method || is_patch_method { "digest " } else { @@ -65,6 +66,8 @@ impl Cybersource { format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n") } else if is_patch_method { format!("(request-target): patch {resource}\ndigest: SHA-256={payload}\n") + } else if is_delete_method { + format!("(request-target): delete {resource}\n") } else { format!("(request-target): get {resource}\n") }; @@ -162,6 +165,28 @@ impl ConnectorCommon for Cybersource { connector_transaction_id: None, }) } + transformers::CybersourceErrorResponse::NotAvailableError(response) => { + let error_response = response + .errors + .iter() + .map(|error_info| { + format!( + "{}: {}", + error_info.error_type.clone().unwrap_or("".to_string()), + error_info.message.clone().unwrap_or("".to_string()) + ) + }) + .collect::<Vec<String>>() + .join(" & "); + Ok(types::ErrorResponse { + status_code: res.status_code, + code: consts::NO_ERROR_CODE.to_string(), + message: error_response.clone(), + reason: Some(error_response), + attempt_status: None, + connector_transaction_id: None, + }) + } } } } @@ -261,6 +286,7 @@ impl api::PaymentIncrementalAuthorization for Cybersource {} impl api::MandateSetup for Cybersource {} impl api::ConnectorAccessToken for Cybersource {} impl api::PaymentToken for Cybersource {} +impl api::ConnectorMandateRevoke for Cybersource {} impl ConnectorIntegration< @@ -347,6 +373,92 @@ impl } } +impl + ConnectorIntegration< + api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > for Cybersource +{ + fn get_headers( + &self, + req: &types::MandateRevokeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + fn get_http_method(&self) -> services::Method { + services::Method::Delete + } + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + fn get_url( + &self, + req: &types::MandateRevokeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}tms/v1/paymentinstruments/{}", + self.base_url(connectors), + connector_utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)? + )) + } + fn build_request( + &self, + req: &types::MandateRevokeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Delete) + .url(&types::MandateRevokeType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::MandateRevokeType::get_headers( + self, req, connectors, + )?) + .build(), + )) + } + fn handle_response( + &self, + data: &types::MandateRevokeRouterData, + res: types::Response, + ) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> { + if matches!(res.status_code, 204) { + Ok(types::MandateRevokeRouterData { + response: Ok(types::MandateRevokeResponseData { + mandate_status: common_enums::MandateStatus::Revoked, + }), + ..data.clone() + }) + } else { + // If http_code != 204 || http_code != 4xx, we dont know any other response scenario yet. + let response_value: serde_json::Value = serde_json::from_slice(&res.response) + .into_report() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; + let response_string = response_value.to_string(); + + Ok(types::MandateRevokeRouterData { + response: Err(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: response_string.clone(), + reason: Some(response_string), + status_code: res.status_code, + attempt_status: None, + connector_transaction_id: None, + }), + ..data.clone() + }) + } + } + fn get_error_response( + &self, + res: types::Response, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Cybersource { diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index a5a0a7237ef..cf769f1a2fd 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1742,6 +1742,20 @@ pub struct CybersourceStandardErrorResponse { pub details: Option<Vec<Details>>, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceNotAvailableErrorResponse { + pub errors: Vec<CybersourceNotAvailableErrorObject>, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CybersourceNotAvailableErrorObject { + #[serde(rename = "type")] + pub error_type: Option<String>, + pub message: Option<String>, +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceServerErrorResponse { @@ -1766,8 +1780,10 @@ pub struct CybersourceAuthenticationErrorResponse { #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum CybersourceErrorResponse { - StandardError(CybersourceStandardErrorResponse), AuthenticationError(CybersourceAuthenticationErrorResponse), + //If the request resource is not available/exists in cybersource + NotAvailableError(CybersourceNotAvailableErrorResponse), + StandardError(CybersourceStandardErrorResponse), } #[derive(Debug, Deserialize, Clone)] diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 0dca3ace947..c44f8cd391e 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -335,6 +335,18 @@ impl PaymentsCaptureRequestData for types::PaymentsCaptureData { } } +pub trait RevokeMandateRequestData { + fn get_connector_mandate_id(&self) -> Result<String, Error>; +} + +impl RevokeMandateRequestData for types::MandateRevokeRequestData { + fn get_connector_mandate_id(&self) -> Result<String, Error> { + self.connector_mandate_id + .clone() + .ok_or_else(missing_field_err("connector_mandate_id")) + } +} + pub trait PaymentsSetupMandateRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_email(&self) -> Result<Email, Error>; diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 55de11549a4..aabd846660c 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -1,13 +1,18 @@ +pub mod utils; + use api_models::payments; use common_utils::{ext_traits::Encode, pii}; use diesel_models::enums as storage_enums; -use error_stack::{report, ResultExt}; +use error_stack::{report, IntoReport, ResultExt}; use futures::future; use router_env::{instrument, logger, tracing}; use super::payments::helpers; use crate::{ - core::errors::{self, RouterResponse, StorageErrorExt}, + core::{ + errors::{self, RouterResponse, StorageErrorExt}, + payments::CallConnectorAction, + }, db::StorageInterface, routes::{metrics, AppState}, services, @@ -16,6 +21,7 @@ use crate::{ api::{ customers, mandates::{self, MandateResponseExt}, + ConnectorData, GetToken, }, domain, storage, transformers::ForeignTryFrom, @@ -44,26 +50,121 @@ pub async fn get_mandate( pub async fn revoke_mandate( state: AppState, merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, req: mandates::MandateId, ) -> RouterResponse<mandates::MandateRevokedResponse> { let db = state.store.as_ref(); let mandate = db - .update_mandate_by_merchant_id_mandate_id( - &merchant_account.merchant_id, - &req.mandate_id, - storage::MandateUpdate::StatusUpdate { - mandate_status: storage::enums::MandateStatus::Revoked, - }, - ) + .find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, &req.mandate_id) .await .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; - Ok(services::ApplicationResponse::Json( - mandates::MandateRevokedResponse { - mandate_id: mandate.mandate_id, - status: mandate.mandate_status, - }, - )) + let mandate_revoke_status = match mandate.mandate_status { + common_enums::MandateStatus::Active + | common_enums::MandateStatus::Inactive + | common_enums::MandateStatus::Pending => { + let profile_id = if let Some(ref payment_id) = mandate.original_payment_id { + let pi = db + .find_payment_intent_by_payment_id_merchant_id( + payment_id, + &merchant_account.merchant_id, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + let profile_id = pi.profile_id.clone().ok_or( + errors::ApiErrorResponse::BusinessProfileNotFound { + id: pi + .profile_id + .unwrap_or_else(|| "Profile id is Null".to_string()), + }, + )?; + Ok(profile_id) + } else { + Err(errors::ApiErrorResponse::PaymentNotFound) + }?; + + let merchant_connector_account = helpers::get_merchant_connector_account( + &state, + &merchant_account.merchant_id, + None, + &key_store, + &profile_id, + &mandate.connector, + mandate.merchant_connector_id.as_ref(), + ) + .await?; + + let connector_data = ConnectorData::get_connector_by_name( + &state.conf.connectors, + &mandate.connector, + GetToken::Connector, + mandate.merchant_connector_id.clone(), + )?; + let connector_integration: services::BoxedConnectorIntegration< + '_, + types::api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > = connector_data.connector.get_connector_integration(); + + let router_data = utils::construct_mandate_revoke_router_data( + merchant_connector_account, + &merchant_account, + mandate.clone(), + ) + .await?; + + let response = services::execute_connector_processing_step( + &state, + connector_integration, + &router_data, + CallConnectorAction::Trigger, + None, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + match response.response { + Ok(_) => { + let update_mandate = db + .update_mandate_by_merchant_id_mandate_id( + &merchant_account.merchant_id, + &req.mandate_id, + storage::MandateUpdate::StatusUpdate { + mandate_status: storage::enums::MandateStatus::Revoked, + }, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?; + Ok(services::ApplicationResponse::Json( + mandates::MandateRevokedResponse { + mandate_id: update_mandate.mandate_id, + status: update_mandate.mandate_status, + error_code: None, + error_message: None, + }, + )) + } + + Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: mandate.connector, + status_code: err.status_code, + reason: err.reason, + }) + .into_report(), + } + } + common_enums::MandateStatus::Revoked => { + Err(errors::ApiErrorResponse::MandateValidationFailed { + reason: "Mandate has already been revoked".to_string(), + }) + .into_report() + } + }; + mandate_revoke_status } #[instrument(skip(db))] diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs new file mode 100644 index 00000000000..25267db1a96 --- /dev/null +++ b/crates/router/src/core/mandate/utils.rs @@ -0,0 +1,76 @@ +use std::marker::PhantomData; + +use common_utils::{errors::CustomResult, ext_traits::ValueExt}; +use diesel_models::Mandate; +use error_stack::ResultExt; + +use crate::{ + core::{errors, payments::helpers}, + types::{self, domain, PaymentAddress}, +}; +const IRRELEVANT_PAYMENT_ID_IN_MANDATE_REVOKE_FLOW: &str = + "irrelevant_payment_id_in_mandate_revoke_flow"; + +const IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW: &str = + "irrelevant_attempt_id_in_mandate_revoke_flow"; + +const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW: &str = + "irrelevant_connector_request_reference_id_in_mandate_revoke_flow"; + +pub async fn construct_mandate_revoke_router_data( + merchant_connector_account: helpers::MerchantConnectorAccountType, + merchant_account: &domain::MerchantAccount, + mandate: Mandate, +) -> CustomResult<types::MandateRevokeRouterData, errors::ApiErrorResponse> { + let auth_type: types::ConnectorAuthType = merchant_connector_account + .get_connector_account_details() + .parse_value("ConnectorAuthType") + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let router_data = types::RouterData { + flow: PhantomData, + merchant_id: merchant_account.merchant_id.clone(), + customer_id: Some(mandate.customer_id), + connector_customer: None, + connector: mandate.connector, + payment_id: mandate + .original_payment_id + .unwrap_or_else(|| IRRELEVANT_PAYMENT_ID_IN_MANDATE_REVOKE_FLOW.to_string()), + attempt_id: IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW.to_string(), + status: diesel_models::enums::AttemptStatus::default(), + payment_method: diesel_models::enums::PaymentMethod::default(), + connector_auth_type: auth_type, + description: None, + return_url: None, + address: PaymentAddress::default(), + auth_type: diesel_models::enums::AuthenticationType::default(), + connector_meta_data: None, + amount_captured: None, + access_token: None, + session_token: None, + reference_id: None, + payment_method_token: None, + recurring_mandate_payment_data: None, + preprocessing_id: None, + payment_method_balance: None, + connector_api_version: None, + request: types::MandateRevokeRequestData { + mandate_id: mandate.mandate_id, + connector_mandate_id: mandate.connector_mandate_id, + }, + response: Err(types::ErrorResponse::get_not_implemented()), + payment_method_id: None, + connector_request_reference_id: + IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW.to_string(), + test_mode: None, + connector_http_status_code: None, + external_latency: None, + apple_pay_flow: None, + frm_metadata: None, + #[cfg(feature = "payouts")] + payout_method_data: None, + #[cfg(feature = "payouts")] + quote_id: None, + }; + + Ok(router_data) +} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index ec8e13cff50..27ddd3f6d81 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -2197,3 +2197,83 @@ default_imp_for_incremental_authorization!( connector::Worldpay, connector::Zen ); + +macro_rules! default_imp_for_revoking_mandates { + ($($path:ident::$connector:ident),*) => { + $( impl api::ConnectorMandateRevoke for $path::$connector {} + impl + services::ConnectorIntegration< + api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > for $path::$connector + {} + )* + }; +} + +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::ConnectorMandateRevoke for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, + > for connector::DummyConnector<T> +{ +} +default_imp_for_revoking_mandates!( + connector::Aci, + connector::Adyen, + connector::Airwallex, + connector::Authorizedotnet, + connector::Bambora, + connector::Bankofamerica, + connector::Bitpay, + connector::Bluesnap, + connector::Boku, + connector::Braintree, + connector::Cashtocode, + connector::Checkout, + connector::Cryptopay, + connector::Coinbase, + connector::Dlocal, + connector::Fiserv, + connector::Forte, + connector::Globalpay, + connector::Globepay, + connector::Gocardless, + connector::Helcim, + connector::Iatapay, + connector::Klarna, + connector::Mollie, + connector::Multisafepay, + connector::Nexinets, + connector::Nmi, + connector::Noon, + connector::Nuvei, + connector::Opayo, + connector::Opennode, + connector::Payeezy, + connector::Payme, + connector::Paypal, + connector::Payu, + connector::Placetopay, + connector::Powertranz, + connector::Prophetpay, + connector::Rapyd, + connector::Riskified, + connector::Signifyd, + connector::Square, + connector::Stax, + connector::Stripe, + connector::Shift4, + connector::Trustpay, + connector::Tsys, + connector::Volt, + connector::Wise, + connector::Worldline, + connector::Worldpay, + connector::Zen +); diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 1e446136297..ecc89a10fa2 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -80,7 +80,9 @@ pub async fn revoke_mandate( state, &req, mandate_id, - |state, auth, req| mandate::revoke_mandate(state, auth.merchant_account, req), + |state, auth, req| { + mandate::revoke_mandate(state, auth.merchant_account, auth.key_store, req) + }, &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, ) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 50aba3de7b5..2225c2965bc 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -19,8 +19,9 @@ use std::{collections::HashMap, marker::PhantomData}; pub use api_models::{ enums::{Connector, PayoutConnectors}, - payouts as payout_types, + mandates, payouts as payout_types, }; +use common_enums::MandateStatus; pub use common_utils::request::{RequestBody, RequestContent}; use common_utils::{pii, pii::Email}; use data_models::mandates::MandateData; @@ -117,6 +118,11 @@ pub type SetupMandateType = dyn services::ConnectorIntegration< SetupMandateRequestData, PaymentsResponseData, >; +pub type MandateRevokeType = dyn services::ConnectorIntegration< + api::MandateRevoke, + MandateRevokeRequestData, + MandateRevokeResponseData, +>; pub type PaymentsPreProcessingType = dyn services::ConnectorIntegration< api::PreProcessing, PaymentsPreProcessingData, @@ -246,6 +252,9 @@ pub type RetrieveFileRouterData = pub type DefendDisputeRouterData = RouterData<api::Defend, DefendDisputeRequestData, DefendDisputeResponse>; +pub type MandateRevokeRouterData = + RouterData<api::MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>; + #[cfg(feature = "payouts")] pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>; @@ -373,8 +382,8 @@ pub struct PayoutsFulfillResponseData { #[derive(Debug, Clone)] pub struct PaymentsAuthorizeData { pub payment_method_data: payments::PaymentMethodData, - /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) - /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately + /// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount) + /// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately /// ``` /// get_original_amount() /// get_surcharge_amount() @@ -957,6 +966,17 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { pub http_code: u16, } +#[derive(Debug, Clone)] +pub struct MandateRevokeRequestData { + pub mandate_id: String, + pub connector_mandate_id: Option<String>, +} + +#[derive(Debug, Clone)] +pub struct MandateRevokeResponseData { + pub mandate_status: MandateStatus, +} + // Different patterns of authentication. #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index fcbd3801c94..b60153eaf19 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -70,6 +70,18 @@ pub trait ConnectorVerifyWebhookSource: { } +#[derive(Clone, Debug)] +pub struct MandateRevoke; + +pub trait ConnectorMandateRevoke: + ConnectorIntegration< + MandateRevoke, + types::MandateRevokeRequestData, + types::MandateRevokeResponseData, +> +{ +} + pub trait ConnectorTransactionId: ConnectorCommon + Sync { fn connector_transaction_id( &self, @@ -159,6 +171,7 @@ pub trait Connector: + Payouts + ConnectorVerifyWebhookSource + FraudCheck + + ConnectorMandateRevoke { } @@ -179,7 +192,8 @@ impl< + ConnectorTransactionId + Payouts + ConnectorVerifyWebhookSource - + FraudCheck, + + FraudCheck + + ConnectorMandateRevoke, > Connector for T { } diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index bf373220fde..d7942c17447 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -6746,6 +6746,18 @@ }, "status": { "$ref": "#/components/schemas/MandateStatus" + }, + "error_code": { + "type": "string", + "description": "If there was an error while calling the connectors the code is received here", + "example": "E0001", + "nullable": true + }, + "error_message": { + "type": "string", + "description": "If there was an error while calling the connector the error message is received here", + "example": "Failed while verifying the card", + "nullable": true } } },
2024-01-07T21:47:25Z
## Description <!-- Describe your changes in detail --> Add Revoke Mandate flow: When the merchant invokes the revoke-mandate endpoint, the mandate should be revoked at both the connector level and core level. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> # ### Revoke a Mandate <img width="1119" alt="Screenshot 2024-01-08 at 12 26 34 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/ed66827d-c74c-4b39-9e42-9bae5d15dc31"> ### Try to revoke already revoked mandate <img width="1123" alt="Screenshot 2024-01-08 at 12 26 45 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/c46cc8a6-26cc-49f0-b3b4-78565364a85e"> ### Make Payment with revoked mandate <img width="1100" alt="Screenshot 2024-01-08 at 12 27 18 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/e74ab57a-27f7-46e8-b01d-46af4b164ed7"> ### Handle Error Response from connector <img width="1160" alt="Screenshot 2024-01-08 at 3 28 17 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/9668538d-c83e-4e64-98d6-f8a6a08e91d8"> ### Not implemented Error <img width="1177" alt="Screenshot 2024-01-08 at 5 58 31 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/82de1e70-6b9f-4d73-a4ec-389b44d69239">
3cd74966b279dc1c43935dc1bceb1c69b9eb0643
- Create a mandate (zero and non-zero) with the connector - Make Payment using the mandates - Revoke the mandate - Try to revoke an already revoked mandate ### Revoke a Mandate <img width="1119" alt="Screenshot 2024-01-08 at 12 26 34 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/ed66827d-c74c-4b39-9e42-9bae5d15dc31"> ### Try to revoke already revoked mandate <img width="1123" alt="Screenshot 2024-01-08 at 12 26 45 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/c46cc8a6-26cc-49f0-b3b4-78565364a85e"> ### Make Payment with revoked mandate <img width="1100" alt="Screenshot 2024-01-08 at 12 27 18 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/e74ab57a-27f7-46e8-b01d-46af4b164ed7"> ### Handle Error Response from connector <img width="1160" alt="Screenshot 2024-01-08 at 3 28 17 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/9668538d-c83e-4e64-98d6-f8a6a08e91d8"> ### Not implemented Error <img width="1177" alt="Screenshot 2024-01-08 at 5 58 31 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/82de1e70-6b9f-4d73-a4ec-389b44d69239">
[ "crates/api_models/src/mandates.rs", "crates/router/src/connector/cybersource.rs", "crates/router/src/connector/cybersource/transformers.rs", "crates/router/src/connector/utils.rs", "crates/router/src/core/mandate.rs", "crates/router/src/core/mandate/utils.rs", "crates/router/src/core/payments/flows.rs"...
juspay/hyperswitch
juspay__hyperswitch-3588
Bug: [BUG] map error message and connector transaction_id in case connector returns failure status in 2xx response status. ### Bug Description When connector returns failure status in 2xx response, error messages are not persisted for some connectors. ### Expected Behavior When connector returns failure status in 2xx response, error messages should be persisted for all connectors. ### Actual Behavior When connector returns failure status in 2xx response, error messages are not persisted for some connectors. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Simulate a failed payment in noon or payme 2. Status will be failed but error message will be null. ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index de53b991d89..b2a9f14ccce 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -1446,9 +1446,9 @@ impl<F> resource_id: types::ResponseId::NoResponseId, redirection_data, mandate_reference: None, - connector_metadata: Some( - serde_json::json!({"three_ds_data":three_ds_data}), - ), + connector_metadata: Some(serde_json::json!({ + "three_ds_data": three_ds_data + })), network_txn_id: None, connector_response_reference_id, incremental_authorization_allowed: None, diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index fb806fda68f..d4697e3ba14 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -4,7 +4,8 @@ use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, CryptoData}, + connector::utils::{self, is_payment_failure, CryptoData}, + consts, core::errors, services, types::{self, api, storage::enums}, @@ -155,14 +156,30 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let redirection_data = item - .response - .data - .hosted_page_url - .map(|x| services::RedirectForm::from((x, services::Method::Get))); - Ok(Self { - status: enums::AttemptStatus::from(item.response.data.status), - response: Ok(types::PaymentsResponseData::TransactionResponse { + let status = enums::AttemptStatus::from(item.response.data.status.clone()); + let response = if is_payment_failure(status) { + let payment_response = &item.response.data; + Err(types::ErrorResponse { + code: payment_response + .name + .clone() + .unwrap_or(consts::NO_ERROR_CODE.to_string()), + message: payment_response + .status_context + .clone() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + reason: payment_response.status_context.clone(), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(payment_response.id.clone()), + }) + } else { + let redirection_data = item + .response + .data + .hosted_page_url + .map(|x| services::RedirectForm::from((x, services::Method::Get))); + Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::ConnectorTransactionId( item.response.data.id.clone(), ), @@ -176,7 +193,11 @@ impl<F, T> .custom_id .or(Some(item.response.data.id)), incremental_authorization_allowed: None, - }), + }) + }; + Ok(Self { + status, + response, ..item.data }) } diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 2f5f342d7ae..bbd7da234b6 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{ - self as conn_utils, CardData, PaymentsAuthorizeRequestData, RevokeMandateRequestData, - RouterData, WalletData, + self as conn_utils, is_refund_failure, CardData, PaymentsAuthorizeRequestData, + RevokeMandateRequestData, RouterData, WalletData, }, core::{errors, mandate::MandateBehaviour}, services, @@ -555,6 +555,8 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, NoonPaymentsResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { + let order = item.response.result.order; + let status = enums::AttemptStatus::foreign_from((order.status, item.data.status)); let redirection_data = item.response.result.checkout_data.map(|redirection_data| { services::RedirectForm::Form { endpoint: redirection_data.post_url.to_string(), @@ -570,17 +572,16 @@ impl<F, T> connector_mandate_id: Some(subscription_data.identifier), payment_method_id: None, }); - let order = item.response.result.order; Ok(Self { - status: enums::AttemptStatus::foreign_from((order.status, item.data.status)), + status, response: match order.error_message { Some(error_message) => Err(ErrorResponse { code: order.error_code.to_string(), message: error_message.clone(), reason: Some(error_message), status_code: item.http_code, - attempt_status: None, - connector_transaction_id: None, + attempt_status: Some(status), + connector_transaction_id: Some(order.id.to_string()), }), _ => { let connector_response_reference_id = @@ -784,13 +785,18 @@ pub struct NoonPaymentsTransactionResponse { } #[derive(Default, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct NoonRefundResponseResult { transaction: NoonPaymentsTransactionResponse, } #[derive(Default, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct RefundResponse { result: NoonRefundResponseResult, + result_code: u32, + class_description: String, + message: String, } impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> @@ -800,11 +806,26 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> fn try_from( item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, ) -> Result<Self, Self::Error> { - Ok(Self { - response: Ok(types::RefundsResponseData { + let response = &item.response; + let refund_status = + enums::RefundStatus::from(response.result.transaction.status.to_owned()); + let response = if is_refund_failure(refund_status) { + Err(ErrorResponse { + status_code: item.http_code, + code: response.result_code.to_string(), + message: response.class_description.clone(), + reason: Some(response.message.clone()), + attempt_status: None, + connector_transaction_id: Some(response.result.transaction.id.clone()), + }) + } else { + Ok(types::RefundsResponseData { connector_refund_id: item.response.result.transaction.id, - refund_status: enums::RefundStatus::from(item.response.result.transaction.status), - }), + refund_status, + }) + }; + Ok(Self { + response, ..item.data }) } @@ -819,13 +840,18 @@ pub struct NoonRefundResponseTransactions { } #[derive(Default, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct NoonRefundSyncResponseResult { transactions: Vec<NoonRefundResponseTransactions>, } #[derive(Default, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct RefundSyncResponse { result: NoonRefundSyncResponseResult, + result_code: u32, + class_description: String, + message: String, } impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>> @@ -849,12 +875,25 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>> }) }) .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; - - Ok(Self { - response: Ok(types::RefundsResponseData { + let refund_status = enums::RefundStatus::from(noon_transaction.status.to_owned()); + let response = if is_refund_failure(refund_status) { + let response = &item.response; + Err(ErrorResponse { + status_code: item.http_code, + code: response.result_code.to_string(), + message: response.class_description.clone(), + reason: Some(response.message.clone()), + attempt_status: None, + connector_transaction_id: Some(noon_transaction.id.clone()), + }) + } else { + Ok(types::RefundsResponseData { connector_refund_id: noon_transaction.id.to_owned(), - refund_status: enums::RefundStatus::from(noon_transaction.status.to_owned()), - }), + refund_status, + }) + }; + Ok(Self { + response, ..item.data }) } diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 77dcb6429c9..e0f13741b64 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -12,9 +12,9 @@ use url::Url; use crate::{ connector::utils::{ - self, missing_field_err, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, - PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, PaymentsSyncRequestData, - RouterData, + self, is_payment_failure, is_refund_failure, missing_field_err, AddressDetailsData, + CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + PaymentsPreProcessingData, PaymentsSyncRequestData, RouterData, }, consts, core::errors, @@ -198,14 +198,15 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, PaymePaySaleResponse, T, types::PaymentsResponseData>, ) -> Result<Self, Self::Error> { - let response = if item.response.sale_status == SaleStatus::Failed { + let status = enums::AttemptStatus::from(item.response.sale_status.clone()); + let response = if is_payment_failure(status) { // To populate error message in case of failure Err(types::ErrorResponse::from((&item.response, item.http_code))) } else { Ok(types::PaymentsResponseData::try_from(&item.response)?) }; Ok(Self { - status: enums::AttemptStatus::from(item.response.sale_status), + status, response, ..item.data }) @@ -227,7 +228,7 @@ impl From<(&PaymePaySaleResponse, u16)> for types::ErrorResponse { reason: pay_sale_response.status_error_details.to_owned(), status_code: http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()), } } } @@ -281,7 +282,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay .first() .cloned() .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; - let response = if transaction_response.sale_status == SaleStatus::Failed { + let status = enums::AttemptStatus::from(transaction_response.sale_status.clone()); + let response = if is_payment_failure(status) { // To populate error message in case of failure Err(types::ErrorResponse::from(( &transaction_response, @@ -291,7 +293,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay Ok(types::PaymentsResponseData::from(&transaction_response)) }; Ok(Self { - status: enums::AttemptStatus::from(transaction_response.sale_status), + status, response, ..item.data }) @@ -312,7 +314,7 @@ impl From<(&SaleQuery, u16)> for types::ErrorResponse { reason: sale_query_response.sale_error_text.clone(), status_code: http_code, attempt_status: None, - connector_transaction_id: None, + connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()), } } } @@ -982,6 +984,7 @@ impl TryFrom<SaleStatus> for enums::RefundStatus { pub struct PaymeRefundResponse { sale_status: SaleStatus, payme_transaction_id: String, + status_error_code: i64, } impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>> @@ -991,11 +994,25 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse> fn try_from( item: types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>, ) -> Result<Self, Self::Error> { - Ok(Self { - response: Ok(types::RefundsResponseData { + let refund_status = enums::RefundStatus::try_from(item.response.sale_status.clone())?; + let response = if is_refund_failure(refund_status) { + let payme_response = &item.response; + Err(types::ErrorResponse { + code: payme_response.status_error_code.to_string(), + message: payme_response.status_error_code.to_string(), + reason: Some(payme_response.status_error_code.to_string()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(payme_response.payme_transaction_id.clone()), + }) + } else { + Ok(types::RefundsResponseData { connector_refund_id: item.response.payme_transaction_id, - refund_status: enums::RefundStatus::try_from(item.response.sale_status)?, - }), + refund_status, + }) + }; + Ok(Self { + response, ..item.data }) } @@ -1031,13 +1048,24 @@ impl<F, T> .items .first() .ok_or(errors::ConnectorError::ResponseHandlingFailed)?; - Ok(Self { - response: Ok(types::RefundsResponseData { - refund_status: enums::RefundStatus::try_from( - pay_sale_response.sale_status.clone(), - )?, + let refund_status = enums::RefundStatus::try_from(pay_sale_response.sale_status.clone())?; + let response = if is_refund_failure(refund_status) { + Err(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: consts::NO_ERROR_CODE.to_string(), + reason: None, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(pay_sale_response.payme_transaction_id.clone()), + }) + } else { + Ok(types::RefundsResponseData { + refund_status, connector_refund_id: pay_sale_response.payme_transaction_id.clone(), - }), + }) + }; + Ok(Self { + response, ..item.data }) } diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 87d50bb68a2..7951246790f 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1786,6 +1786,7 @@ pub fn is_refund_failure(status: enums::RefundStatus) -> bool { | common_enums::RefundStatus::Success => false, } } + #[cfg(test)] mod error_code_error_message_tests { #![allow(clippy::unwrap_used)]
2024-01-06T08:14:41Z
## Description <!-- Describe your changes in detail --> Store payment_id and refund_id and error_details in case connector returns 2xx for a failed payment. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
5fb3c001b5dc371f81fe1708fd9a6c6978fb726e
Manual Noon: <img width="1310" alt="noon error mapping" src="https://github.com/juspay/hyperswitch/assets/61539176/84877c5e-ea00-45c9-b32b-fc514859512d"> Payme: <img width="1347" alt="payme error mapping" src="https://github.com/juspay/hyperswitch/assets/61539176/18e9fb84-bba8-48b7-8859-ce1eabe1aef8"> Refund: Noon: Refund create <img width="1728" alt="Noon refund creat" src="https://github.com/juspay/hyperswitch/assets/61539176/c199585a-ed3a-428c-9d44-228f39dc93e9"> Noon: Refund force sync <img width="1728" alt="Noon refund force sync" src="https://github.com/juspay/hyperswitch/assets/61539176/571dc7ae-d1de-4155-8f7e-523476c32b7a"> Payme: refund create: <img width="1728" alt="payme refund create" src="https://github.com/juspay/hyperswitch/assets/61539176/ff640556-e23a-4a54-b327-a8e2f34dfd77"> Payme: refund Force sync <img width="1728" alt="payme refund force sync" src="https://github.com/juspay/hyperswitch/assets/61539176/f93bcd2e-50c2-46f5-b117-e41c669a5639">
[ "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/cryptopay/transformers.rs", "crates/router/src/connector/noon/transformers.rs", "crates/router/src/connector/payme/transformers.rs", "crates/router/src/connector/utils.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3251
Bug: Rename `kms` feature flag to `aws_kms` Rename `kms` feature flag to `aws_kms`, `kms` files to `aws_kms` and the components of kms to include `aws` as its prefix. This change is required so that current kms encryption becomes distinguishable, especially if in future new encryption implementations like a AWS KMS alternative is integrated.
diff --git a/README.md b/README.md index 0f5e924589f..0da065eeba6 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ should be introduced, checking it agrees with the actual structure --> │ ├── data_models : Represents the data/domain models used by the business/domain layer │ ├── diesel_models : Database models shared across `router` and other crates │ ├── drainer : Application that reads Redis streams and executes queries in database -│ ├── external_services : Interactions with external systems like emails, KMS, etc. +│ ├── external_services : Interactions with external systems like emails, AWS KMS, etc. │ ├── masking : Personal Identifiable Information protection │ ├── redis_interface : A user-friendly interface to Redis │ ├── router : Main crate of the project diff --git a/config/config.example.toml b/config/config.example.toml index 87999f0e9e9..027adee5f68 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -322,7 +322,7 @@ paypal = { currency = "USD,INR", country = "US" } # ^------------------------------- any valid payment method type (can be multiple) (for cards this should be card_network) # If either currency or country isn't provided then, all possible values are accepted -# KMS configuration. Only applicable when the `kms` feature flag is enabled. +# AWS KMS configuration. Only applicable when the `aws_kms` feature flag is enabled. [kms] key_id = "" # The AWS key ID used by the KMS SDK for decrypting data. region = "" # The AWS region used by the KMS SDK for decrypting data. diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 67169a15104..adffb39875d 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -8,8 +8,8 @@ readme = "README.md" license.workspace = true [features] -release = ["kms", "vergen"] -kms = ["external_services/kms"] +release = ["aws_kms", "vergen"] +aws_kms = ["external_services/aws_kms"] hashicorp-vault = ["external_services/hashicorp-vault"] vergen = ["router_env/vergen"] diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs index 6af0a978223..788ff1456e2 100644 --- a/crates/drainer/src/connection.rs +++ b/crates/drainer/src/connection.rs @@ -1,10 +1,10 @@ use bb8::PooledConnection; use diesel::PgConnection; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::{self, decrypt::VaultFetch, Kv2}; -#[cfg(feature = "kms")] -use external_services::kms::{self, decrypt::KmsDecrypt}; -#[cfg(not(feature = "kms"))] +#[cfg(not(feature = "aws_kms"))] use masking::PeekInterface; use crate::settings::Database; @@ -28,7 +28,7 @@ pub async fn redis_connection( pub async fn diesel_make_pg_pool( database: &Database, _test_transaction: bool, - #[cfg(feature = "kms")] kms_client: &'static kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &'static aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hashicorp_client: &'static hashicorp_vault::HashiCorpVault, ) -> PgPool { let password = database.password.clone(); @@ -38,13 +38,13 @@ pub async fn diesel_make_pg_pool( .await .expect("Failed while fetching db password"); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let password = password - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .expect("Failed to decrypt password"); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let password = &password.peek(); let database_url = format!( diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index 4393ebb9dc9..77ee980e901 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -27,8 +27,8 @@ impl Store { master_pool: diesel_make_pg_pool( &config.master_database, test_transaction, - #[cfg(feature = "kms")] - external_services::kms::get_kms_client(&config.kms).await, + #[cfg(feature = "aws_kms")] + external_services::aws_kms::get_aws_kms_client(&config.kms).await, #[cfg(feature = "hashicorp-vault")] #[allow(clippy::expect_used)] external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault) diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 5b80ee375f5..a60612f8b24 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -2,10 +2,10 @@ use std::path::PathBuf; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; -#[cfg(feature = "kms")] -use external_services::kms; use redis_interface as redis; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use router_env::{env, logger}; @@ -13,9 +13,9 @@ use serde::Deserialize; use crate::errors; -#[cfg(feature = "kms")] -pub type Password = kms::KmsValue; -#[cfg(not(feature = "kms"))] +#[cfg(feature = "aws_kms")] +pub type Password = aws_kms::AwsKmsValue; +#[cfg(not(feature = "aws_kms"))] pub type Password = masking::Secret<String>; #[derive(clap::Parser, Default)] @@ -34,8 +34,8 @@ pub struct Settings { pub redis: redis::RedisSettings, pub log: Log, pub drainer: DrainerSettings, - #[cfg(feature = "kms")] - pub kms: kms::KmsConfig, + #[cfg(feature = "aws_kms")] + pub kms: aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, } diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index bf836af71a7..2b6bc22b2e9 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" license.workspace = true [features] -kms = ["dep:aws-config", "dep:aws-sdk-kms"] +aws_kms = ["dep:aws-config", "dep:aws-sdk-kms"] email = ["dep:aws-config"] aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = [ "dep:vaultrs" ] diff --git a/crates/external_services/src/kms.rs b/crates/external_services/src/aws_kms.rs similarity index 69% rename from crates/external_services/src/kms.rs rename to crates/external_services/src/aws_kms.rs index 740bca4d821..cf21f36f22b 100644 --- a/crates/external_services/src/kms.rs +++ b/crates/external_services/src/aws_kms.rs @@ -14,18 +14,20 @@ pub mod decrypt; use crate::{consts, metrics}; -static KMS_CLIENT: tokio::sync::OnceCell<KmsClient> = tokio::sync::OnceCell::const_new(); +static AWS_KMS_CLIENT: tokio::sync::OnceCell<AwsKmsClient> = tokio::sync::OnceCell::const_new(); -/// Returns a shared KMS client, or initializes a new one if not previously initialized. +/// Returns a shared AWS KMS client, or initializes a new one if not previously initialized. #[inline] -pub async fn get_kms_client(config: &KmsConfig) -> &'static KmsClient { - KMS_CLIENT.get_or_init(|| KmsClient::new(config)).await +pub async fn get_aws_kms_client(config: &AwsKmsConfig) -> &'static AwsKmsClient { + AWS_KMS_CLIENT + .get_or_init(|| AwsKmsClient::new(config)) + .await } -/// Configuration parameters required for constructing a [`KmsClient`]. +/// Configuration parameters required for constructing a [`AwsKmsClient`]. #[derive(Clone, Debug, Default, serde::Deserialize)] #[serde(default)] -pub struct KmsConfig { +pub struct AwsKmsConfig { /// The AWS key identifier of the KMS key used to encrypt or decrypt data. pub key_id: String, @@ -33,16 +35,16 @@ pub struct KmsConfig { pub region: String, } -/// Client for KMS operations. +/// Client for AWS KMS operations. #[derive(Debug)] -pub struct KmsClient { +pub struct AwsKmsClient { inner_client: Client, key_id: String, } -impl KmsClient { - /// Constructs a new KMS client. - pub async fn new(config: &KmsConfig) -> Self { +impl AwsKmsClient { + /// Constructs a new AWS KMS client. + pub async fn new(config: &AwsKmsConfig) -> Self { let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone())); let sdk_config = aws_config::from_env().region(region_provider).load().await; @@ -56,12 +58,12 @@ impl KmsClient { /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in /// a machine that is able to assume an IAM role. - pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, KmsError> { + pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> { let start = Instant::now(); let data = consts::BASE64_ENGINE .decode(data) .into_report() - .change_context(KmsError::Base64DecodingFailed)?; + .change_context(AwsKmsError::Base64DecodingFailed)?; let ciphertext_blob = Blob::new(data); let decrypt_output = self @@ -74,21 +76,21 @@ impl KmsClient { .map_err(|error| { // Logging using `Debug` representation of the error as the `Display` // representation does not hold sufficient information. - logger::error!(kms_sdk_error=?error, "Failed to KMS decrypt data"); + logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS decrypt data"); metrics::AWS_KMS_DECRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); error }) .into_report() - .change_context(KmsError::DecryptionFailed)?; + .change_context(AwsKmsError::DecryptionFailed)?; let output = decrypt_output .plaintext - .ok_or(KmsError::MissingPlaintextDecryptionOutput) + .ok_or(AwsKmsError::MissingPlaintextDecryptionOutput) .into_report() .and_then(|blob| { String::from_utf8(blob.into_inner()) .into_report() - .change_context(KmsError::Utf8DecodingFailed) + .change_context(AwsKmsError::Utf8DecodingFailed) })?; let time_taken = start.elapsed(); @@ -101,7 +103,7 @@ impl KmsClient { /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in /// a machine that is able to assume an IAM role. - pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, KmsError> { + pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> { let start = Instant::now(); let plaintext_blob = Blob::new(data.as_ref()); @@ -115,16 +117,16 @@ impl KmsClient { .map_err(|error| { // Logging using `Debug` representation of the error as the `Display` // representation does not hold sufficient information. - logger::error!(kms_sdk_error=?error, "Failed to KMS encrypt data"); + logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS encrypt data"); metrics::AWS_KMS_ENCRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); error }) .into_report() - .change_context(KmsError::EncryptionFailed)?; + .change_context(AwsKmsError::EncryptionFailed)?; let output = encrypted_output .ciphertext_blob - .ok_or(KmsError::MissingCiphertextEncryptionOutput) + .ok_or(AwsKmsError::MissingCiphertextEncryptionOutput) .into_report() .map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?; let time_taken = start.elapsed(); @@ -134,9 +136,9 @@ impl KmsClient { } } -/// Errors that could occur during KMS operations. +/// Errors that could occur during AWS KMS operations. #[derive(Debug, thiserror::Error)] -pub enum KmsError { +pub enum AwsKmsError { /// An error occurred when base64 encoding input data. #[error("Failed to base64 encode input data")] Base64EncodingFailed, @@ -145,33 +147,33 @@ pub enum KmsError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, - /// An error occurred when KMS decrypting input data. - #[error("Failed to KMS decrypt input data")] + /// An error occurred when AWS KMS decrypting input data. + #[error("Failed to AWS KMS decrypt input data")] DecryptionFailed, - /// An error occurred when KMS encrypting input data. - #[error("Failed to KMS encrypt input data")] + /// An error occurred when AWS KMS encrypting input data. + #[error("Failed to AWS KMS encrypt input data")] EncryptionFailed, - /// The KMS decrypted output does not include a plaintext output. - #[error("Missing plaintext KMS decryption output")] + /// The AWS KMS decrypted output does not include a plaintext output. + #[error("Missing plaintext AWS KMS decryption output")] MissingPlaintextDecryptionOutput, - /// The KMS encrypted output does not include a ciphertext output. - #[error("Missing ciphertext KMS encryption output")] + /// The AWS KMS encrypted output does not include a ciphertext output. + #[error("Missing ciphertext AWS KMS encryption output")] MissingCiphertextEncryptionOutput, - /// An error occurred UTF-8 decoding KMS decrypted output. + /// An error occurred UTF-8 decoding AWS KMS decrypted output. #[error("Failed to UTF-8 decode decryption output")] Utf8DecodingFailed, - /// The KMS client has not been initialized. - #[error("The KMS client has not been initialized")] - KmsClientNotInitialized, + /// The AWS KMS client has not been initialized. + #[error("The AWS KMS client has not been initialized")] + AwsKmsClientNotInitialized, } -impl KmsConfig { - /// Verifies that the [`KmsClient`] configuration is usable. +impl AwsKmsConfig { + /// Verifies that the [`AwsKmsClient`] configuration is usable. pub fn validate(&self) -> Result<(), &'static str> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; @@ -185,18 +187,24 @@ impl KmsConfig { } } -/// A wrapper around a KMS value that can be decrypted. +/// A wrapper around a AWS KMS value that can be decrypted. #[derive(Clone, Debug, Default, serde::Deserialize, Eq, PartialEq)] #[serde(transparent)] -pub struct KmsValue(Secret<String>); +pub struct AwsKmsValue(Secret<String>); -impl From<String> for KmsValue { +impl common_utils::ext_traits::ConfigExt for AwsKmsValue { + fn is_empty_after_trim(&self) -> bool { + self.0.peek().is_empty_after_trim() + } +} + +impl From<String> for AwsKmsValue { fn from(value: String) -> Self { Self(Secret::new(value)) } } -impl From<Secret<String>> for KmsValue { +impl From<Secret<String>> for AwsKmsValue { fn from(value: Secret<String>) -> Self { Self(value) } @@ -204,7 +212,7 @@ impl From<Secret<String>> for KmsValue { #[cfg(feature = "hashicorp-vault")] #[async_trait::async_trait] -impl super::hashicorp_vault::decrypt::VaultFetch for KmsValue { +impl super::hashicorp_vault::decrypt::VaultFetch for AwsKmsValue { async fn fetch_inner<En>( self, client: &super::hashicorp_vault::HashiCorpVault, @@ -224,13 +232,7 @@ impl super::hashicorp_vault::decrypt::VaultFetch for KmsValue { >, > + 'a, { - self.0.fetch_inner::<En>(client).await.map(KmsValue) - } -} - -impl common_utils::ext_traits::ConfigExt for KmsValue { - fn is_empty_after_trim(&self) -> bool { - self.0.peek().is_empty_after_trim() + self.0.fetch_inner::<En>(client).await.map(AwsKmsValue) } } @@ -238,44 +240,44 @@ impl common_utils::ext_traits::ConfigExt for KmsValue { mod tests { #![allow(clippy::expect_used)] #[tokio::test] - async fn check_kms_encryption() { + async fn check_aws_kms_encryption() { std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); use super::*; - let config = KmsConfig { - key_id: "YOUR KMS KEY ID".to_string(), + let config = AwsKmsConfig { + key_id: "YOUR AWS KMS KEY ID".to_string(), region: "AWS REGION".to_string(), }; let data = "hello".to_string(); let binding = data.as_bytes(); - let kms_encrypted_fingerprint = KmsClient::new(&config) + let kms_encrypted_fingerprint = AwsKmsClient::new(&config) .await .encrypt(binding) .await - .expect("kms encryption failed"); + .expect("aws kms encryption failed"); println!("{}", kms_encrypted_fingerprint); } #[tokio::test] - async fn check_kms_decrypt() { + async fn check_aws_kms_decrypt() { std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); use super::*; - let config = KmsConfig { - key_id: "YOUR KMS KEY ID".to_string(), + let config = AwsKmsConfig { + key_id: "YOUR AWS KMS KEY ID".to_string(), region: "AWS REGION".to_string(), }; // Should decrypt to hello - let data = "KMS ENCRYPTED CIPHER".to_string(); + let data = "AWS KMS ENCRYPTED CIPHER".to_string(); let binding = data.as_bytes(); - let kms_encrypted_fingerprint = KmsClient::new(&config) + let kms_encrypted_fingerprint = AwsKmsClient::new(&config) .await .decrypt(binding) .await - .expect("kms decryption failed"); + .expect("aws kms decryption failed"); println!("{}", kms_encrypted_fingerprint); } diff --git a/crates/external_services/src/aws_kms/decrypt.rs b/crates/external_services/src/aws_kms/decrypt.rs new file mode 100644 index 00000000000..9abd4fefbef --- /dev/null +++ b/crates/external_services/src/aws_kms/decrypt.rs @@ -0,0 +1,42 @@ +use common_utils::errors::CustomResult; + +use super::*; + +#[async_trait::async_trait] +/// This trait performs in place decryption of the structure on which this is implemented +pub trait AwsKmsDecrypt { + /// The output type of the decryption + type Output; + /// Decrypts the structure given a AWS KMS client + async fn decrypt_inner( + self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> + where + Self: Sized; + + /// Tries to use the Singleton client to decrypt the structure + async fn try_decrypt_inner(self) -> CustomResult<Self::Output, AwsKmsError> + where + Self: Sized, + { + let client = AWS_KMS_CLIENT + .get() + .ok_or(AwsKmsError::AwsKmsClientNotInitialized)?; + self.decrypt_inner(client).await + } +} + +#[async_trait::async_trait] +impl AwsKmsDecrypt for &AwsKmsValue { + type Output = String; + async fn decrypt_inner( + self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + aws_kms_client + .decrypt(self.0.peek()) + .await + .attach_printable("Failed to decrypt AWS KMS value") + } +} diff --git a/crates/external_services/src/kms/decrypt.rs b/crates/external_services/src/kms/decrypt.rs deleted file mode 100644 index 0749745affc..00000000000 --- a/crates/external_services/src/kms/decrypt.rs +++ /dev/null @@ -1,34 +0,0 @@ -use common_utils::errors::CustomResult; - -use super::*; - -#[async_trait::async_trait] -/// This trait performs in place decryption of the structure on which this is implemented -pub trait KmsDecrypt { - /// The output type of the decryption - type Output; - /// Decrypts the structure given a KMS client - async fn decrypt_inner(self, kms_client: &KmsClient) -> CustomResult<Self::Output, KmsError> - where - Self: Sized; - - /// Tries to use the Singleton client to decrypt the structure - async fn try_decrypt_inner(self) -> CustomResult<Self::Output, KmsError> - where - Self: Sized, - { - let client = KMS_CLIENT.get().ok_or(KmsError::KmsClientNotInitialized)?; - self.decrypt_inner(client).await - } -} - -#[async_trait::async_trait] -impl KmsDecrypt for &KmsValue { - type Output = String; - async fn decrypt_inner(self, kms_client: &KmsClient) -> CustomResult<Self::Output, KmsError> { - kms_client - .decrypt(self.0.peek()) - .await - .attach_printable("Failed to decrypt KMS value") - } -} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index bba65873e91..cdabdeb49ae 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -6,15 +6,15 @@ #[cfg(feature = "email")] pub mod email; -#[cfg(feature = "kms")] -pub mod kms; +#[cfg(feature = "aws_kms")] +pub mod aws_kms; pub mod file_storage; #[cfg(feature = "hashicorp-vault")] pub mod hashicorp_vault; /// Crate specific constants -#[cfg(feature = "kms")] +#[cfg(feature = "aws_kms")] pub mod consts { /// General purpose base64 engine pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose = @@ -22,20 +22,20 @@ pub mod consts { } /// Metrics for interactions with external systems. -#[cfg(feature = "kms")] +#[cfg(feature = "aws_kms")] pub mod metrics { use router_env::{counter_metric, global_meter, histogram_metric, metrics_context}; metrics_context!(CONTEXT); global_meter!(GLOBAL_METER, "EXTERNAL_SERVICES"); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures - #[cfg(feature = "kms")] - histogram_metric!(AWS_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for KMS decryption time (in sec) - #[cfg(feature = "kms")] - histogram_metric!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for KMS encryption time (in sec) + #[cfg(feature = "aws_kms")] + histogram_metric!(AWS_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS decryption time (in sec) + #[cfg(feature = "aws_kms")] + histogram_metric!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS encryption time (in sec) } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index f60b0c25e93..9b345217bb5 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -11,12 +11,12 @@ license.workspace = true [features] default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] aws_s3 = ["external_services/aws_s3"] -kms = ["external_services/kms"] +aws_kms = ["external_services/aws_kms"] hashicorp-vault = ["external_services/hashicorp-vault"] email = ["external_services/email", "olap"] frm = [] stripe = ["dep:serde_qs"] -release = ["kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] +release = ["aws_kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap","api_models/olap","dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] diff --git a/crates/router/src/configs.rs b/crates/router/src/configs.rs index 5cb1df0644e..d069c89b82e 100644 --- a/crates/router/src/configs.rs +++ b/crates/router/src/configs.rs @@ -1,7 +1,7 @@ +#[cfg(feature = "aws_kms")] +pub mod aws_kms; mod defaults; #[cfg(feature = "hashicorp-vault")] pub mod hc_vault; -#[cfg(feature = "kms")] -pub mod kms; pub mod settings; mod validations; diff --git a/crates/router/src/configs/aws_kms.rs b/crates/router/src/configs/aws_kms.rs new file mode 100644 index 00000000000..5e37f2a4dd6 --- /dev/null +++ b/crates/router/src/configs/aws_kms.rs @@ -0,0 +1,107 @@ +use common_utils::errors::CustomResult; +use external_services::aws_kms::{decrypt::AwsKmsDecrypt, AwsKmsClient, AwsKmsError}; +use masking::ExposeInterface; + +use crate::configs::settings; + +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::Jwekey { + type Output = Self; + + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + ( + self.vault_encryption_key, + self.rust_locker_encryption_key, + self.vault_private_key, + self.tunnel_private_key, + ) = tokio::try_join!( + aws_kms_client.decrypt(self.vault_encryption_key), + aws_kms_client.decrypt(self.rust_locker_encryption_key), + aws_kms_client.decrypt(self.vault_private_key), + aws_kms_client.decrypt(self.tunnel_private_key), + )?; + Ok(self) + } +} + +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::ActiveKmsSecrets { + type Output = Self; + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + self.jwekey = self + .jwekey + .expose() + .decrypt_inner(aws_kms_client) + .await? + .into(); + Ok(self) + } +} + +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::Database { + type Output = storage_impl::config::Database; + + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + Ok(storage_impl::config::Database { + host: self.host, + port: self.port, + dbname: self.dbname, + username: self.username, + password: self.password.decrypt_inner(aws_kms_client).await?.into(), + pool_size: self.pool_size, + connection_timeout: self.connection_timeout, + queue_strategy: self.queue_strategy, + min_idle: self.min_idle, + max_lifetime: self.max_lifetime, + }) + } +} + +#[cfg(feature = "olap")] +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::PayPalOnboarding { + type Output = Self; + + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + self.client_id = aws_kms_client + .decrypt(self.client_id.expose()) + .await? + .into(); + self.client_secret = aws_kms_client + .decrypt(self.client_secret.expose()) + .await? + .into(); + self.partner_id = aws_kms_client + .decrypt(self.partner_id.expose()) + .await? + .into(); + Ok(self) + } +} + +#[cfg(feature = "olap")] +#[async_trait::async_trait] +impl AwsKmsDecrypt for settings::ConnectorOnboarding { + type Output = Self; + + async fn decrypt_inner( + mut self, + aws_kms_client: &AwsKmsClient, + ) -> CustomResult<Self::Output, AwsKmsError> { + self.paypal = self.paypal.decrypt_inner(aws_kms_client).await?; + Ok(self) + } +} diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 7b88c9c2dc7..fc5ba0f55bc 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -1,8 +1,8 @@ use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; -#[cfg(feature = "kms")] -use external_services::kms::KmsValue; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::AwsKmsValue; use super::settings::{ConnectorFields, Password, PaymentMethodType, RequiredFieldFinal}; @@ -6235,12 +6235,12 @@ impl Default for super::settings::RequiredFields { impl Default for super::settings::ApiKeys { fn default() -> Self { Self { - #[cfg(feature = "kms")] - kms_encrypted_hash_key: KmsValue::default(), + #[cfg(feature = "aws_kms")] + kms_encrypted_hash_key: AwsKmsValue::default(), // Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating // hashes of API keys - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] hash_key: String::new(), // Specifies the number of days before API key expiry when email reminders should be sent diff --git a/crates/router/src/configs/kms.rs b/crates/router/src/configs/kms.rs deleted file mode 100644 index 4e236a512ac..00000000000 --- a/crates/router/src/configs/kms.rs +++ /dev/null @@ -1,96 +0,0 @@ -use common_utils::errors::CustomResult; -use external_services::kms::{decrypt::KmsDecrypt, KmsClient, KmsError}; -use masking::ExposeInterface; - -use crate::configs::settings; - -#[async_trait::async_trait] -impl KmsDecrypt for settings::Jwekey { - type Output = Self; - - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - ( - self.vault_encryption_key, - self.rust_locker_encryption_key, - self.vault_private_key, - self.tunnel_private_key, - ) = tokio::try_join!( - kms_client.decrypt(self.vault_encryption_key), - kms_client.decrypt(self.rust_locker_encryption_key), - kms_client.decrypt(self.vault_private_key), - kms_client.decrypt(self.tunnel_private_key), - )?; - Ok(self) - } -} - -#[async_trait::async_trait] -impl KmsDecrypt for settings::ActiveKmsSecrets { - type Output = Self; - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - self.jwekey = self.jwekey.expose().decrypt_inner(kms_client).await?.into(); - Ok(self) - } -} - -#[async_trait::async_trait] -impl KmsDecrypt for settings::Database { - type Output = storage_impl::config::Database; - - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - Ok(storage_impl::config::Database { - host: self.host, - port: self.port, - dbname: self.dbname, - username: self.username, - password: self.password.decrypt_inner(kms_client).await?.into(), - pool_size: self.pool_size, - connection_timeout: self.connection_timeout, - queue_strategy: self.queue_strategy, - min_idle: self.min_idle, - max_lifetime: self.max_lifetime, - }) - } -} - -#[cfg(feature = "olap")] -#[async_trait::async_trait] -impl KmsDecrypt for settings::PayPalOnboarding { - type Output = Self; - - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - self.client_id = kms_client.decrypt(self.client_id.expose()).await?.into(); - self.client_secret = kms_client - .decrypt(self.client_secret.expose()) - .await? - .into(); - self.partner_id = kms_client.decrypt(self.partner_id.expose()).await?.into(); - Ok(self) - } -} - -#[cfg(feature = "olap")] -#[async_trait::async_trait] -impl KmsDecrypt for settings::ConnectorOnboarding { - type Output = Self; - - async fn decrypt_inner( - mut self, - kms_client: &KmsClient, - ) -> CustomResult<Self::Output, KmsError> { - self.paypal = self.paypal.decrypt_inner(kms_client).await?; - Ok(self) - } -} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index dd6eaa104cb..2519455f95a 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -8,13 +8,13 @@ use analytics::ReportConfig; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "email")] use external_services::email::EmailSettings; use external_services::file_storage::FileStorageConfig; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; -#[cfg(feature = "kms")] -use external_services::kms; use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; @@ -29,9 +29,9 @@ use crate::{ env::{self, logger, Env}, events::EventsConfig, }; -#[cfg(feature = "kms")] -pub type Password = kms::KmsValue; -#[cfg(not(feature = "kms"))] +#[cfg(feature = "aws_kms")] +pub type Password = aws_kms::AwsKmsValue; +#[cfg(not(feature = "aws_kms"))] pub type Password = masking::Secret<String>; #[derive(clap::Parser, Default)] @@ -53,8 +53,8 @@ pub enum Subcommand { GenerateOpenapiSpec, } -#[cfg(feature = "kms")] -/// Store the decrypted kms secret values for active use in the application +#[cfg(feature = "aws_kms")] +/// Store the decrypted aws kms secret values for active use in the application /// Currently using `StrongSecret` won't have any effect as this struct have smart pointers to heap /// allocations. /// note: we can consider adding such behaviour in the future with custom implementation @@ -88,8 +88,8 @@ pub struct Settings { pub pm_filters: ConnectorFilters, pub bank_config: BankRedirectConfig, pub api_keys: ApiKeys, - #[cfg(feature = "kms")] - pub kms: kms::KmsConfig, + #[cfg(feature = "aws_kms")] + pub kms: aws_kms::AwsKmsConfig, pub file_storage: FileStorageConfig, #[cfg(feature = "hashicorp-vault")] pub hc_vault: hashicorp_vault::HashiCorpVaultConfig, @@ -359,19 +359,19 @@ pub struct RequiredFieldFinal { #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct Secrets { - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] pub jwt_secret: String, - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] pub admin_api_key: String, - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] pub recon_admin_api_key: String, pub master_enc_key: Password, - #[cfg(feature = "kms")] - pub kms_encrypted_jwt_secret: kms::KmsValue, - #[cfg(feature = "kms")] - pub kms_encrypted_admin_api_key: kms::KmsValue, - #[cfg(feature = "kms")] - pub kms_encrypted_recon_admin_api_key: kms::KmsValue, + #[cfg(feature = "aws_kms")] + pub kms_encrypted_jwt_secret: aws_kms::AwsKmsValue, + #[cfg(feature = "aws_kms")] + pub kms_encrypted_admin_api_key: aws_kms::AwsKmsValue, + #[cfg(feature = "aws_kms")] + pub kms_encrypted_recon_admin_api_key: aws_kms::AwsKmsValue, } #[derive(Debug, Deserialize, Clone)] @@ -441,7 +441,7 @@ pub struct Database { pub max_lifetime: Option<u64>, } -#[cfg(not(feature = "kms"))] +#[cfg(not(feature = "aws_kms"))] impl From<Database> for storage_impl::config::Database { fn from(val: Database) -> Self { Self { @@ -596,12 +596,12 @@ pub struct WebhookIgnoreErrorSettings { pub struct ApiKeys { /// Base64-encoded (KMS encrypted) ciphertext of the key used for calculating hashes of API /// keys - #[cfg(feature = "kms")] - pub kms_encrypted_hash_key: kms::KmsValue, + #[cfg(feature = "aws_kms")] + pub kms_encrypted_hash_key: aws_kms::AwsKmsValue, /// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating /// hashes of API keys - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] pub hash_key: String, // Specifies the number of days before API key expiry when email reminders should be sent @@ -712,7 +712,7 @@ impl Settings { #[cfg(feature = "kv_store")] self.drainer.validate()?; self.api_keys.validate()?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] self.kms .validate() .map_err(|error| ApplicationError::InvalidConfigurationValueError(error.into()))?; diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 910ae754347..a4eb3f3c66e 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -5,7 +5,7 @@ impl super::settings::Secrets { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] { when(self.jwt_secret.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( @@ -20,7 +20,7 @@ impl super::settings::Secrets { })?; } - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] { when(self.kms_encrypted_jwt_secret.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( @@ -131,14 +131,14 @@ impl super::settings::ApiKeys { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] return when(self.kms_encrypted_hash_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty when KMS feature is enabled".into(), )) }); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] when(self.hash_key.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty".into(), diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 9bdc493e078..58f95e1371e 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -35,7 +35,7 @@ pub mod user; #[cfg(feature = "olap")] pub mod user_role; pub mod utils; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] pub mod verification; #[cfg(feature = "olap")] pub mod verify_connector; diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index f28d845609a..162f8bed0f8 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -2,11 +2,11 @@ use common_utils::date_time; #[cfg(feature = "email")] use diesel_models::{api_keys::ApiKey, enums as storage_enums}; use error_stack::{report, IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms; -#[cfg(not(feature = "kms"))] +#[cfg(not(feature = "aws_kms"))] use masking::ExposeInterface; use masking::{PeekInterface, StrongSecret}; use router_env::{instrument, tracing}; @@ -30,26 +30,26 @@ const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY"; #[cfg(feature = "email")] const API_KEY_EXPIRY_RUNNER: &str = "API_KEY_EXPIRY_WORKFLOW"; -#[cfg(feature = "kms")] -use external_services::kms::decrypt::KmsDecrypt; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::decrypt::AwsKmsDecrypt; static HASH_KEY: tokio::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> = tokio::sync::OnceCell::const_new(); pub async fn get_hash_key( api_key_config: &settings::ApiKeys, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hc_client: &external_services::hashicorp_vault::HashiCorpVault, ) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> { HASH_KEY .get_or_try_init(|| async { let hash_key = { - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] { api_key_config.kms_encrypted_hash_key.clone() } - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] { masking::Secret::<_, masking::WithType>::new(api_key_config.hash_key.clone()) } @@ -61,14 +61,14 @@ pub async fn get_hash_key( .await .change_context(errors::ApiErrorResponse::InternalServerError)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let hash_key = hash_key - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to KMS decrypt API key hashing key")?; + .attach_printable("Failed to AWS KMS decrypt API key hashing key")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let hash_key = hash_key.expose(); <[u8; PlaintextApiKey::HASH_KEY_LEN]>::try_from( @@ -153,7 +153,7 @@ impl PlaintextApiKey { #[instrument(skip_all)] pub async fn create_api_key( state: AppState, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hc_client: &external_services::hashicorp_vault::HashiCorpVault, api_key: api::CreateApiKeyRequest, @@ -175,8 +175,8 @@ pub async fn create_api_key( let hash_key = get_hash_key( api_key_config, - #[cfg(feature = "kms")] - kms_client, + #[cfg(feature = "aws_kms")] + aws_kms_client, #[cfg(feature = "hashicorp-vault")] hc_client, ) @@ -589,8 +589,8 @@ mod tests { let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH); let hash_key = get_hash_key( &settings.api_keys, - #[cfg(feature = "kms")] - external_services::kms::get_kms_client(&settings.kms).await, + #[cfg(feature = "aws_kms")] + external_services::aws_kms::get_aws_kms_client(&settings.kms).await, #[cfg(feature = "hashicorp-vault")] external_services::hashicorp_vault::get_hashicorp_client(&settings.hc_vault) .await diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs index b7effaf63ac..0e452a90f48 100644 --- a/crates/router/src/core/blocklist/utils.rs +++ b/crates/router/src/core/blocklist/utils.rs @@ -1,8 +1,8 @@ use api_models::blocklist as api_blocklist; use common_utils::crypto::{self, SignMessage}; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "kms")] -use external_services::kms; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; use super::{errors, AppState}; use crate::{ @@ -38,15 +38,15 @@ pub async fn delete_entry_from_blocklist( message: "blocklist record with given fingerprint id not found".to_string(), })?; - #[cfg(feature = "kms")] - let decrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let decrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(blocklist_fingerprint.encrypted_fingerprint) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to kms decrypt fingerprint")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; let blocklist_entry = state @@ -184,15 +184,15 @@ pub async fn insert_entry_into_blocklist( message: "fingerprint not found".to_string(), })?; - #[cfg(feature = "kms")] - let decrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let decrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(blocklist_fingerprint.encrypted_fingerprint) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to kms decrypt encrypted fingerprint")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; state diff --git a/crates/router/src/core/currency.rs b/crates/router/src/core/currency.rs index 41699df47a7..b0d06f9fd65 100644 --- a/crates/router/src/core/currency.rs +++ b/crates/router/src/core/currency.rs @@ -17,7 +17,7 @@ pub async fn retrieve_forex( state.conf.forex_api.call_delay, state.conf.forex_api.local_fetch_retry_delay, state.conf.forex_api.local_fetch_retry_count, - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] &state.conf.kms, #[cfg(feature = "hashicorp-vault")] &state.conf.hc_vault, @@ -44,7 +44,7 @@ pub async fn convert_forex( amount, to_currency, from_currency, - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] &state.conf.kms, #[cfg(feature = "hashicorp-vault")] &state.conf.hc_vault, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 9052893d4a9..c7486e827c2 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -221,12 +221,12 @@ pub enum VaultError { } #[derive(Debug, thiserror::Error)] -pub enum KmsError { +pub enum AwsKmsError { #[error("Failed to base64 decode input data")] Base64DecodingFailed, - #[error("Failed to KMS decrypt input data")] + #[error("Failed to AWS KMS decrypt input data")] DecryptionFailed, - #[error("Missing plaintext KMS decryption output")] + #[error("Missing plaintext AWS KMS decryption output")] MissingPlaintextDecryptionOutput, #[error("Failed to UTF-8 decode decryption output")] Utf8DecodingFailed, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 5797fd60da0..4bc0490e7d1 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -603,9 +603,9 @@ pub async fn get_payment_method_from_hs_locker<'a>( locker_choice: Option<api_enums::LockerChoice>, ) -> errors::CustomResult<Secret<String>, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwekey = &state.conf.jwekey; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwekey = &state.kms_secrets; let payment_method_data = if !locker.mock_locker { @@ -661,9 +661,9 @@ pub async fn call_to_locker_hs<'a>( locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwekey = &state.conf.jwekey; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwekey = &state.kms_secrets; let db = &*state.store; let stored_card_response = if !locker.mock_locker { @@ -722,9 +722,9 @@ pub async fn get_card_from_hs_locker<'a>( locker_choice: api_enums::LockerChoice, ) -> errors::CustomResult<payment_methods::Card, errors::VaultError> { let locker = &state.conf.locker; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwekey = &state.conf.jwekey; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwekey = &state.kms_secrets; if !locker.mock_locker { @@ -777,9 +777,9 @@ pub async fn delete_card_from_hs_locker<'a>( card_reference: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { let locker = &state.conf.locker; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwekey = &state.conf.jwekey; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwekey = &state.kms_secrets; let request = payment_methods::mk_delete_card_request_hs( diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 304091e42ac..12bb5981b1c 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -186,14 +186,14 @@ pub fn get_dotted_jws(jws: encryption::JwsBody) -> String { } pub async fn get_decrypted_response_payload( - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, jwe_body: encryption::JweBody, locker_choice: Option<api_enums::LockerChoice>, ) -> CustomResult<String, errors::VaultError> { let target_locker = locker_choice.unwrap_or(api_enums::LockerChoice::Basilisk); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let public_key = match target_locker { api_enums::LockerChoice::Basilisk => jwekey.jwekey.peek().vault_encryption_key.as_bytes(), api_enums::LockerChoice::Tartarus => { @@ -201,16 +201,16 @@ pub async fn get_decrypted_response_payload( } }; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let public_key = match target_locker { api_enums::LockerChoice::Basilisk => jwekey.vault_encryption_key.as_bytes(), api_enums::LockerChoice::Tartarus => jwekey.rust_locker_encryption_key.as_bytes(), }; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = jwekey.vault_private_key.as_bytes(); let jwt = get_dotted_jwe(jwe_body); @@ -237,8 +237,8 @@ pub async fn get_decrypted_response_payload( } pub async fn mk_basilisk_req( - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, jws: &str, locker_choice: api_enums::LockerChoice, ) -> CustomResult<encryption::JweBody, errors::VaultError> { @@ -257,7 +257,7 @@ pub async fn mk_basilisk_req( let payload = utils::Encode::<encryption::JwsBody>::encode_to_vec(&jws_body) .change_context(errors::VaultError::SaveCardFailed)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let public_key = match locker_choice { api_enums::LockerChoice::Basilisk => jwekey.jwekey.peek().vault_encryption_key.as_bytes(), api_enums::LockerChoice::Tartarus => { @@ -265,7 +265,7 @@ pub async fn mk_basilisk_req( } }; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let public_key = match locker_choice { api_enums::LockerChoice::Basilisk => jwekey.vault_encryption_key.as_bytes(), api_enums::LockerChoice::Tartarus => jwekey.rust_locker_encryption_key.as_bytes(), @@ -293,8 +293,8 @@ pub async fn mk_basilisk_req( } pub async fn mk_add_locker_request_hs<'a>( - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, locker: &settings::Locker, payload: &StoreLockerReq<'a>, locker_choice: api_enums::LockerChoice, @@ -302,10 +302,10 @@ pub async fn mk_add_locker_request_hs<'a>( let payload = utils::Encode::<StoreCardReq<'_>>::encode_to_vec(&payload) .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = jwekey.vault_private_key.as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) @@ -463,8 +463,8 @@ pub fn mk_add_card_request( } pub async fn mk_get_card_request_hs( - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, locker: &settings::Locker, customer_id: &str, merchant_id: &str, @@ -480,10 +480,10 @@ pub async fn mk_get_card_request_hs( let payload = utils::Encode::<CardReqBody<'_>>::encode_to_vec(&card_req_body) .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = jwekey.vault_private_key.as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) @@ -540,8 +540,8 @@ pub fn mk_get_card_response(card: GetCardResponse) -> errors::RouterResult<Card> } pub async fn mk_delete_card_request_hs( - #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, - #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, + #[cfg(feature = "aws_kms")] jwekey: &settings::ActiveKmsSecrets, + #[cfg(not(feature = "aws_kms"))] jwekey: &settings::Jwekey, locker: &settings::Locker, customer_id: &str, merchant_id: &str, @@ -556,10 +556,10 @@ pub async fn mk_delete_card_request_hs( let payload = utils::Encode::<CardReqBody<'_>>::encode_to_vec(&card_req_body) .change_context(errors::VaultError::RequestEncodingFailed)?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = jwekey.jwekey.peek().vault_private_key.as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = jwekey.vault_private_key.as_bytes(); let jws = encryption::jws_sign_payload(&payload, &locker.locker_signing_key_id, private_key) diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 099c266e04f..062c58e056c 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -2,12 +2,12 @@ use api_models::payments as payment_types; use async_trait::async_trait; use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; use error_stack::{IntoReport, Report, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms; #[cfg(feature = "hashicorp-vault")] use masking::ExposeInterface; @@ -258,17 +258,18 @@ async fn create_applepay_session_token( } .await?; - #[cfg(feature = "kms")] - let decrypted_apple_pay_merchant_cert = kms::get_kms_client(&state.conf.kms) - .await - .decrypt(apple_pay_merchant_cert) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Apple pay merchant certificate decryption failed")?; + #[cfg(feature = "aws_kms")] + let decrypted_apple_pay_merchant_cert = + aws_kms::get_aws_kms_client(&state.conf.kms) + .await + .decrypt(apple_pay_merchant_cert) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Apple pay merchant certificate decryption failed")?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let decrypted_apple_pay_merchant_cert_key = - kms::get_kms_client(&state.conf.kms) + aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(apple_pay_merchant_cert_key) .await @@ -277,15 +278,16 @@ async fn create_applepay_session_token( "Apple pay merchant certificate key decryption failed", )?; - #[cfg(feature = "kms")] - let decrypted_merchant_identifier = kms::get_kms_client(&state.conf.kms) - .await - .decrypt(common_merchant_identifier) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Apple pay merchant identifier decryption failed")?; + #[cfg(feature = "aws_kms")] + let decrypted_merchant_identifier = + aws_kms::get_aws_kms_client(&state.conf.kms) + .await + .decrypt(common_merchant_identifier) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Apple pay merchant identifier decryption failed")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_merchant_identifier = common_merchant_identifier; let apple_pay_session_request = get_session_request_for_simplified_apple_pay( @@ -293,10 +295,10 @@ async fn create_applepay_session_token( session_token_data, ); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_apple_pay_merchant_cert = apple_pay_merchant_cert; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_apple_pay_merchant_cert_key = apple_pay_merchant_cert_key; ( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index fe4a7757ecc..5d801063e6e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -13,12 +13,12 @@ use data_models::{ use diesel_models::enums; // TODO : Evaluate all the helper functions () use error_stack::{report, IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms; use josekit::jwe; use masking::{ExposeInterface, PeekInterface}; use openssl::{ @@ -2888,7 +2888,7 @@ pub async fn get_merchant_connector_account( }, )?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let private_key = state .kms_secrets .jwekey @@ -2896,7 +2896,7 @@ pub async fn get_merchant_connector_account( .tunnel_private_key .as_bytes(); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let private_key = state.conf.jwekey.tunnel_private_key.as_bytes(); let decrypted_mca = services::decrypt_jwe(mca_config.config.as_str(), services::KeyIdCheck::SkipKeyIdCheck, private_key, jwe::RSA_OAEP_256) @@ -3556,14 +3556,14 @@ impl ApplePayData { } .await?; - #[cfg(feature = "kms")] - let cert_data = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let cert_data = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(&apple_pay_ppc) .await .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let cert_data = &apple_pay_ppc; let base64_decode_cert_data = BASE64_ENGINE @@ -3640,14 +3640,14 @@ impl ApplePayData { } .await?; - #[cfg(feature = "kms")] - let decrypted_apple_pay_ppc_key = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let decrypted_apple_pay_ppc_key = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(&apple_pay_ppc_key) .await .change_context(errors::ApplePayDecryptionError::DecryptionFailed)?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let decrypted_apple_pay_ppc_key = &apple_pay_ppc_key; // Create PKey objects from EcKey let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes()) diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 151078a6056..486a60f7bc3 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -7,8 +7,8 @@ use common_utils::{ ext_traits::{AsyncExt, Encode}, }; use error_stack::{report, IntoReport, ResultExt}; -#[cfg(feature = "kms")] -use external_services::kms; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; use futures::FutureExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; @@ -869,8 +869,8 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> } if let Some(encoded_hash) = card_number_fingerprint { - #[cfg(feature = "kms")] - let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let encrypted_fingerprint = aws_kms::get_aws_kms_client(&state.conf.kms) .await .encrypt(encoded_hash) .await @@ -882,7 +882,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> Some, ); - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let encrypted_fingerprint = Some(encoded_hash); if let Some(encrypted_fingerprint) = encrypted_fingerprint { diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 9f70cc6baee..f77d5120812 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -19,8 +19,8 @@ use common_utils::{ }; use data_models::payments::PaymentIntent; use error_stack::{IntoReport, ResultExt}; -#[cfg(feature = "kms")] -pub use external_services::kms; +#[cfg(feature = "aws_kms")] +pub use external_services::aws_kms; use helpers::PaymentAuthConnectorDataExt; use masking::{ExposeInterface, PeekInterface}; use pm_auth::{ @@ -368,8 +368,8 @@ async fn store_bank_details_in_payment_methods( } .await?; - #[cfg(feature = "kms")] - let pm_auth_key = kms::get_kms_client(&state.conf.kms) + #[cfg(feature = "aws_kms")] + let pm_auth_key = aws_kms::get_aws_kms_client(&state.conf.kms) .await .decrypt(pm_auth_key) .await diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs index bac47b34dce..0ed70e6e0c6 100644 --- a/crates/router/src/core/verification.rs +++ b/crates/router/src/core/verification.rs @@ -2,8 +2,8 @@ pub mod utils; use api_models::verifications::{self, ApplepayMerchantResponse}; use common_utils::{errors::CustomResult, request::RequestContent}; use error_stack::ResultExt; -#[cfg(feature = "kms")] -use external_services::kms; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; use crate::{core::errors::api_error_response, headers, logger, routes::AppState, services}; @@ -13,7 +13,7 @@ pub async fn verify_merchant_creds_for_applepay( state: AppState, _req: &actix_web::HttpRequest, body: verifications::ApplepayMerchantVerificationRequest, - kms_config: &kms::KmsConfig, + kms_config: &aws_kms::AwsKmsConfig, merchant_id: String, ) -> CustomResult< services::ApplicationResponse<ApplepayMerchantResponse>, @@ -27,19 +27,19 @@ pub async fn verify_merchant_creds_for_applepay( let encrypted_key = &state.conf.applepay_merchant_configs.merchant_cert_key; let applepay_endpoint = &state.conf.applepay_merchant_configs.applepay_endpoint; - let applepay_internal_merchant_identifier = kms::get_kms_client(kms_config) + let applepay_internal_merchant_identifier = aws_kms::get_aws_kms_client(kms_config) .await .decrypt(encrypted_merchant_identifier) .await .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; - let cert_data = kms::get_kms_client(kms_config) + let cert_data = aws_kms::get_aws_kms_client(kms_config) .await .decrypt(encrypted_cert) .await .change_context(api_error_response::ApiErrorResponse::InternalServerError)?; - let key_data = kms::get_kms_client(kms_config) + let key_data = aws_kms::get_aws_kms_client(kms_config) .await .decrypt(encrypted_key) .await diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index bb56a173da3..1c80aff4397 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -142,7 +142,7 @@ pub fn mk_app( .service(routes::ConnectorOnboarding::server(state.clone())) } - #[cfg(all(feature = "olap", feature = "kms"))] + #[cfg(all(feature = "olap", feature = "aws_kms"))] { server_app = server_app.service(routes::Verify::server(state.clone())); } diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index d9916f98e74..e058d4f1c1b 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -37,7 +37,7 @@ pub mod routing; pub mod user; #[cfg(feature = "olap")] pub mod user_role; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] pub mod verification; #[cfg(feature = "olap")] pub mod verify_connector; @@ -57,7 +57,7 @@ pub use self::app::Forex; pub use self::app::Payouts; #[cfg(all(feature = "olap", feature = "recon"))] pub use self::app::Recon; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] pub use self::app::Verify; pub use self::app::{ ApiKeys, AppState, BusinessProfile, Cache, Cards, Configs, ConnectorOnboarding, Customers, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index fb1851af00d..cf859d048dd 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -44,8 +44,9 @@ pub async fn api_key_create( &req, payload, |state, _, payload| async { - #[cfg(feature = "kms")] - let kms_client = external_services::kms::get_kms_client(&state.clone().conf.kms).await; + #[cfg(feature = "aws_kms")] + let aws_kms_client = + external_services::aws_kms::get_aws_kms_client(&state.clone().conf.kms).await; #[cfg(feature = "hashicorp-vault")] let hc_client = external_services::hashicorp_vault::get_hashicorp_client( @@ -56,8 +57,8 @@ pub async fn api_key_create( api_keys::create_api_key( state, - #[cfg(feature = "kms")] - kms_client, + #[cfg(feature = "aws_kms")] + aws_kms_client, #[cfg(feature = "hashicorp-vault")] hc_client, payload, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9e8bee73c28..70cd68dfacc 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1,16 +1,19 @@ use std::sync::Arc; use actix_web::{web, Scope}; -#[cfg(all(feature = "olap", any(feature = "hashicorp-vault", feature = "kms")))] +#[cfg(all( + feature = "olap", + any(feature = "hashicorp-vault", feature = "aws_kms") +))] use analytics::AnalyticsConfig; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "email")] use external_services::email::{ses::AwsSes, EmailService}; use external_services::file_storage::FileStorageInterface; #[cfg(all(feature = "olap", feature = "hashicorp-vault"))] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms::{self, decrypt::KmsDecrypt}; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] use masking::PeekInterface; use router_env::tracing_actix_web::RequestId; use scheduler::SchedulerInterface; @@ -29,7 +32,7 @@ use super::payouts::*; use super::pm_auth; #[cfg(feature = "olap")] use super::routing as cloud_routing; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains}; #[cfg(feature = "olap")] use super::{ @@ -63,7 +66,7 @@ pub struct AppState { pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<dyn EmailService>, - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] pub kms_secrets: Arc<settings::ActiveKmsSecrets>, pub api_client: Box<dyn crate::services::ApiClient>, #[cfg(feature = "olap")] @@ -141,15 +144,15 @@ impl AppState { /// /// Panics if Store can't be created or JWE decryption fails pub async fn with_storage( - #[cfg_attr(not(all(feature = "olap", feature = "kms")), allow(unused_mut))] + #[cfg_attr(not(all(feature = "olap", feature = "aws_kms")), allow(unused_mut))] mut conf: settings::Settings, storage_impl: StorageImpl, shut_down_signal: oneshot::Sender<()>, api_client: Box<dyn crate::services::ApiClient>, ) -> Self { Box::pin(async move { - #[cfg(feature = "kms")] - let kms_client = kms::get_kms_client(&conf.kms).await; + #[cfg(feature = "aws_kms")] + let aws_kms_client = aws_kms::get_aws_kms_client(&conf.kms).await; #[cfg(all(feature = "hashicorp-vault", feature = "olap"))] #[allow(clippy::expect_used)] let hc_client = @@ -207,14 +210,14 @@ impl AppState { } }; - #[cfg(all(feature = "kms", feature = "olap"))] + #[cfg(all(feature = "aws_kms", feature = "olap"))] #[allow(clippy::expect_used)] match conf.analytics { AnalyticsConfig::Clickhouse { .. } => {} AnalyticsConfig::Sqlx { ref mut sqlx } | AnalyticsConfig::CombinedCkh { ref mut sqlx, .. } | AnalyticsConfig::CombinedSqlx { ref mut sqlx, .. } => { - sqlx.password = kms_client + sqlx.password = aws_kms_client .decrypt(&sqlx.password.peek()) .await .expect("Failed to decrypt password") @@ -232,12 +235,12 @@ impl AppState { .expect("Failed to decrypt connector onboarding credentials"); } - #[cfg(all(feature = "kms", feature = "olap"))] + #[cfg(all(feature = "aws_kms", feature = "olap"))] #[allow(clippy::expect_used)] { conf.connector_onboarding = conf .connector_onboarding - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .expect("Failed to decrypt connector onboarding credentials"); } @@ -256,14 +259,14 @@ impl AppState { .expect("Failed to decrypt connector onboarding credentials"); } - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] #[allow(clippy::expect_used)] let kms_secrets = settings::ActiveKmsSecrets { jwekey: conf.jwekey.clone().into(), } - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await - .expect("Failed while performing KMS decryption"); + .expect("Failed while performing AWS KMS decryption"); #[cfg(feature = "email")] let email_client = Arc::new(create_email_client(&conf).await); @@ -276,7 +279,7 @@ impl AppState { conf: Arc::new(conf), #[cfg(feature = "email")] email_client, - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] kms_secrets: Arc::new(kms_secrets), api_client, event_handler, @@ -934,10 +937,10 @@ impl Gsm { } } -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] pub struct Verify; -#[cfg(all(feature = "olap", feature = "kms"))] +#[cfg(all(feature = "olap", feature = "aws_kms"))] impl Verify { pub fn server(state: AppState) -> Scope { web::scope("/verify") diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 6c3293dba9d..c4d0420a9b5 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -5,9 +5,9 @@ global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses -#[cfg(feature = "kms")] +#[cfg(feature = "aws_kms")] counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures -#[cfg(feature = "kms")] +#[cfg(feature = "aws_kms")] counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures // API Level Metrics diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index c0ed2b442d0..220fde4631f 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -13,14 +13,14 @@ pub mod recon; #[cfg(feature = "email")] pub mod email; -#[cfg(any(feature = "kms", feature = "hashicorp-vault"))] +#[cfg(any(feature = "aws_kms", feature = "hashicorp-vault"))] use data_models::errors::StorageError; use data_models::errors::StorageResult; use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms::{self, decrypt::KmsDecrypt}; use masking::{PeekInterface, StrongSecret}; #[cfg(feature = "kv_store")] use storage_impl::KVRouterStore; @@ -45,8 +45,8 @@ pub async fn get_store( shut_down_signal: oneshot::Sender<()>, test_transaction: bool, ) -> StorageResult<Store> { - #[cfg(feature = "kms")] - let kms_client = kms::get_kms_client(&config.kms).await; + #[cfg(feature = "aws_kms")] + let aws_kms_client = aws_kms::get_aws_kms_client(&config.kms).await; #[cfg(feature = "hashicorp-vault")] let hc_client = external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault) @@ -62,9 +62,9 @@ pub async fn get_store( .change_context(StorageError::InitializationError) .attach_printable("Failed to fetch data from hashicorp vault")?; - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let master_config = master_config - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to decrypt master database config")?; @@ -79,17 +79,17 @@ pub async fn get_store( .change_context(StorageError::InitializationError) .attach_printable("Failed to fetch data from hashicorp vault")?; - #[cfg(all(feature = "olap", feature = "kms"))] + #[cfg(all(feature = "olap", feature = "aws_kms"))] let replica_config = replica_config - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(StorageError::InitializationError) .attach_printable("Failed to decrypt replica database config")?; let master_enc_key = get_master_enc_key( config, - #[cfg(feature = "kms")] - kms_client, + #[cfg(feature = "aws_kms")] + aws_kms_client, #[cfg(feature = "hashicorp-vault")] hc_client, ) @@ -128,7 +128,7 @@ pub async fn get_store( #[allow(clippy::expect_used)] async fn get_master_enc_key( conf: &crate::configs::settings::Settings, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hc_client: &external_services::hashicorp_vault::HashiCorpVault, ) -> StrongSecret<Vec<u8>> { @@ -140,10 +140,10 @@ async fn get_master_enc_key( .await .expect("Failed to fetch master enc key"); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let master_enc_key = masking::Secret::<_, masking::WithType>::new( master_enc_key - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .expect("Failed to decrypt master enc key"), ); diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 221106612f3..308ceb2672b 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -3,10 +3,10 @@ use api_models::{payment_methods::PaymentMethodListRequest, payments}; use async_trait::async_trait; use common_utils::date_time; use error_stack::{report, IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms::{self, decrypt::AwsKmsDecrypt}; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::decrypt::VaultFetch; -#[cfg(feature = "kms")] -use external_services::kms::{self, decrypt::KmsDecrypt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; #[cfg(feature = "hashicorp-vault")] use masking::ExposeInterface; @@ -225,8 +225,8 @@ where let config = state.conf(); api_keys::get_hash_key( &config.api_keys, - #[cfg(feature = "kms")] - kms::get_kms_client(&config.kms).await, + #[cfg(feature = "aws_kms")] + aws_kms::get_aws_kms_client(&config.kms).await, #[cfg(feature = "hashicorp-vault")] external_services::hashicorp_vault::get_hashicorp_client(&config.hc_vault) .await @@ -289,22 +289,22 @@ static ADMIN_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = pub async fn get_admin_api_key( secrets: &settings::Secrets, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, #[cfg(feature = "hashicorp-vault")] hc_client: &external_services::hashicorp_vault::HashiCorpVault, ) -> RouterResult<&'static StrongSecret<String>> { ADMIN_API_KEY .get_or_try_init(|| async { - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let admin_api_key = secrets.admin_api_key.clone(); - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let admin_api_key = secrets .kms_encrypted_admin_api_key - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to KMS decrypt admin API key")?; + .attach_printable("Failed to AWS KMS decrypt admin API key")?; #[cfg(feature = "hashicorp-vault")] let admin_api_key = masking::Secret::new(admin_api_key) @@ -368,8 +368,8 @@ where let admin_api_key = get_admin_api_key( &conf.secrets, - #[cfg(feature = "kms")] - kms::get_kms_client(&conf.kms).await, + #[cfg(feature = "aws_kms")] + aws_kms::get_aws_kms_client(&conf.kms).await, #[cfg(feature = "hashicorp-vault")] external_services::hashicorp_vault::get_hashicorp_client(&conf.hc_vault) .await @@ -873,19 +873,19 @@ static JWT_SECRET: tokio::sync::OnceCell<StrongSecret<String>> = tokio::sync::On pub async fn get_jwt_secret( secrets: &settings::Secrets, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] aws_kms_client: &aws_kms::AwsKmsClient, ) -> RouterResult<&'static StrongSecret<String>> { JWT_SECRET .get_or_try_init(|| async { - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let jwt_secret = secrets .kms_encrypted_jwt_secret - .decrypt_inner(kms_client) + .decrypt_inner(aws_kms_client) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to KMS decrypt JWT secret")?; + .attach_printable("Failed to AWS KMS decrypt JWT secret")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let jwt_secret = secrets.jwt_secret.clone(); Ok(StrongSecret::new(jwt_secret)) @@ -900,8 +900,8 @@ where let conf = state.conf(); let secret = get_jwt_secret( &conf.secrets, - #[cfg(feature = "kms")] - kms::get_kms_client(&conf.kms).await, + #[cfg(feature = "aws_kms")] + aws_kms::get_aws_kms_client(&conf.kms).await, ) .await? .peek() @@ -972,11 +972,11 @@ static RECON_API_KEY: tokio::sync::OnceCell<StrongSecret<String>> = #[cfg(feature = "recon")] pub async fn get_recon_admin_api_key( secrets: &settings::Secrets, - #[cfg(feature = "kms")] kms_client: &kms::KmsClient, + #[cfg(feature = "aws_kms")] kms_client: &aws_kms::AwsKmsClient, ) -> RouterResult<&'static StrongSecret<String>> { RECON_API_KEY .get_or_try_init(|| async { - #[cfg(feature = "kms")] + #[cfg(feature = "aws_kms")] let recon_admin_api_key = secrets .kms_encrypted_recon_admin_api_key .decrypt_inner(kms_client) @@ -984,7 +984,7 @@ pub async fn get_recon_admin_api_key( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to KMS decrypt recon admin API key")?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let recon_admin_api_key = secrets.recon_admin_api_key.clone(); Ok(StrongSecret::new(recon_admin_api_key)) @@ -1012,8 +1012,8 @@ where let admin_api_key = get_recon_admin_api_key( &conf.secrets, - #[cfg(feature = "kms")] - kms::get_kms_client(&conf.kms).await, + #[cfg(feature = "aws_kms")] + aws_kms::get_aws_kms_client(&conf.kms).await, ) .await?; diff --git a/crates/router/src/services/jwt.rs b/crates/router/src/services/jwt.rs index b69a2158391..08db52e4020 100644 --- a/crates/router/src/services/jwt.rs +++ b/crates/router/src/services/jwt.rs @@ -26,8 +26,8 @@ where { let jwt_secret = authentication::get_jwt_secret( &settings.secrets, - #[cfg(feature = "kms")] - external_services::kms::get_kms_client(&settings.kms).await, + #[cfg(feature = "aws_kms")] + external_services::aws_kms::get_aws_kms_client(&settings.kms).await, ) .await .change_context(UserErrors::InternalServerError) diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index a01f2520b6a..057805a76f0 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -4,10 +4,10 @@ use api_models::enums; use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt}; use currency_conversion::types::{CurrencyFactors, ExchangeRates}; use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "aws_kms")] +use external_services::aws_kms; #[cfg(feature = "hashicorp-vault")] use external_services::hashicorp_vault::{self, decrypt::VaultFetch}; -#[cfg(feature = "kms")] -use external_services::kms; use masking::PeekInterface; use once_cell::sync::Lazy; use redis_interface::DelReply; @@ -65,8 +65,8 @@ pub enum ForexCacheError { LocalWriteError, #[error("Json Parsing error")] ParsingError, - #[error("Kms decryption error")] - KmsDecryptionFailed, + #[error("Aws Kms decryption error")] + AwsKmsDecryptionFailed, #[error("Error connecting to redis")] RedisConnectionError, #[error("Not able to release write lock")] @@ -128,7 +128,7 @@ async fn waited_fetch_and_update_caches( state: &AppState, local_fetch_retry_delay: u64, local_fetch_retry_count: u64, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -151,8 +151,8 @@ async fn waited_fetch_and_update_caches( successive_fetch_and_save_forex( state, None, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -192,7 +192,7 @@ pub async fn get_forex_rates( call_delay: i64, local_fetch_retry_delay: u64, local_fetch_retry_count: u64, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -203,8 +203,8 @@ pub async fn get_forex_rates( state, call_delay, local_rates, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -220,8 +220,8 @@ pub async fn get_forex_rates( call_delay, local_fetch_retry_delay, local_fetch_retry_count, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -234,7 +234,7 @@ async fn handler_local_no_data( call_delay: i64, _local_fetch_retry_delay: u64, _local_fetch_retry_count: u64, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -244,8 +244,8 @@ async fn handler_local_no_data( state, data, call_delay, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -256,8 +256,8 @@ async fn handler_local_no_data( Ok(successive_fetch_and_save_forex( state, None, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -268,8 +268,8 @@ async fn handler_local_no_data( Ok(successive_fetch_and_save_forex( state, None, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -281,7 +281,7 @@ async fn handler_local_no_data( async fn successive_fetch_and_save_forex( state: &AppState, stale_redis_data: Option<FxExchangeRatesCacheEntry>, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -292,8 +292,8 @@ async fn successive_fetch_and_save_forex( } let api_rates = fetch_forex_rates( state, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -305,8 +305,8 @@ async fn successive_fetch_and_save_forex( logger::error!(?err); let secondary_api_rates = fallback_fetch_forex_rates( state, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -351,7 +351,7 @@ async fn fallback_forex_redis_check( state: &AppState, redis_data: FxExchangeRatesCacheEntry, call_delay: i64, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -367,8 +367,8 @@ async fn fallback_forex_redis_check( successive_fetch_and_save_forex( state, Some(redis_data), - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -381,7 +381,7 @@ async fn handler_local_expired( state: &AppState, call_delay: i64, local_rates: FxExchangeRatesCacheEntry, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -400,8 +400,8 @@ async fn handler_local_expired( successive_fetch_and_save_forex( state, Some(local_rates), - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -415,8 +415,8 @@ async fn handler_local_expired( successive_fetch_and_save_forex( state, Some(local_rates), - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) @@ -427,7 +427,7 @@ async fn handler_local_expired( async fn fetch_forex_rates( state: &AppState, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, @@ -436,7 +436,7 @@ async fn fetch_forex_rates( #[cfg(feature = "hashicorp-vault")] let client = hashicorp_vault::get_hashicorp_client(hc_config) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; #[cfg(not(feature = "hashicorp-vault"))] let output = state.conf.forex_api.api_key.clone(); @@ -448,19 +448,19 @@ async fn fetch_forex_rates( .clone() .fetch_inner::<hashicorp_vault::Kv2>(client) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; Ok::<_, error_stack::Report<ForexCacheError>>(output) } .await?; - #[cfg(feature = "kms")] - let forex_api_key = kms::get_kms_client(kms_config) + #[cfg(feature = "aws_kms")] + let forex_api_key = aws_kms::get_aws_kms_client(aws_kms_config) .await .decrypt(forex_api_key.peek()) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let forex_api_key = forex_api_key.peek(); let forex_url: String = format!("{}{}{}", FOREX_BASE_URL, forex_api_key, FOREX_BASE_CURRENCY); @@ -516,7 +516,7 @@ async fn fetch_forex_rates( pub async fn fallback_fetch_forex_rates( state: &AppState, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { @@ -524,7 +524,7 @@ pub async fn fallback_fetch_forex_rates( #[cfg(feature = "hashicorp-vault")] let client = hashicorp_vault::get_hashicorp_client(hc_config) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; #[cfg(not(feature = "hashicorp-vault"))] let output = state.conf.forex_api.fallback_api_key.clone(); @@ -536,19 +536,19 @@ pub async fn fallback_fetch_forex_rates( .clone() .fetch_inner::<hashicorp_vault::Kv2>(client) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; Ok::<_, error_stack::Report<ForexCacheError>>(output) } .await?; - #[cfg(feature = "kms")] - let fallback_forex_api_key = kms::get_kms_client(kms_config) + #[cfg(feature = "aws_kms")] + let fallback_forex_api_key = aws_kms::get_aws_kms_client(aws_kms_config) .await .decrypt(fallback_api_key.peek()) .await - .change_context(ForexCacheError::KmsDecryptionFailed)?; + .change_context(ForexCacheError::AwsKmsDecryptionFailed)?; - #[cfg(not(feature = "kms"))] + #[cfg(not(feature = "aws_kms"))] let fallback_forex_api_key = fallback_api_key.peek(); let fallback_forex_url: String = @@ -691,7 +691,7 @@ pub async fn convert_currency( amount: i64, to_currency: String, from_currency: String, - #[cfg(feature = "kms")] kms_config: &kms::KmsConfig, + #[cfg(feature = "aws_kms")] aws_kms_config: &aws_kms::AwsKmsConfig, #[cfg(feature = "hashicorp-vault")] hc_config: &external_services::hashicorp_vault::HashiCorpVaultConfig, ) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexCacheError> { @@ -700,8 +700,8 @@ pub async fn convert_currency( state.conf.forex_api.call_delay, state.conf.forex_api.local_fetch_retry_delay, state.conf.forex_api.local_fetch_retry_count, - #[cfg(feature = "kms")] - kms_config, + #[cfg(feature = "aws_kms")] + aws_kms_config, #[cfg(feature = "hashicorp-vault")] hc_config, ) diff --git a/crates/scheduler/src/configs/settings.rs b/crates/scheduler/src/configs/settings.rs index 723ef81e70c..0135c9dcf45 100644 --- a/crates/scheduler/src/configs/settings.rs +++ b/crates/scheduler/src/configs/settings.rs @@ -1,11 +1,5 @@ -#[cfg(feature = "kms")] -use external_services::kms; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use serde::Deserialize; -#[cfg(feature = "kms")] -pub type Password = kms::KmsValue; -#[cfg(not(feature = "kms"))] -pub type Password = masking::Secret<String>; #[derive(Debug, Clone, Deserialize)] #[serde(default)]
2024-01-04T20:00:07Z
## Description <!-- Describe your changes in detail --> This PR renames `kms` feature flag to `aws_kms`, `kms` files to `aws_kms` and the components of kms to include `aws` as its prefix. This change is done so that current kms encryption is distinguishable, especially if in future new encryption implementations like a AWS KMS alternative is integrated. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
892b04f805c219e2cf7cbe5736aef19909e986f7
Renaming types so just a basic sanity test should suffice
[ "README.md", "config/config.example.toml", "crates/drainer/Cargo.toml", "crates/drainer/src/connection.rs", "crates/drainer/src/services.rs", "crates/drainer/src/settings.rs", "crates/external_services/Cargo.toml", "crates/external_services/src/kms.rs", "crates/external_services/src/aws_kms/decrypt....
juspay/hyperswitch
juspay__hyperswitch-3322
Bug: fix: reset tracking id api for connector onboarding ## Problem To support the onboarding flow where merchants can signin/signup directly into the connector's website and give us the credentials of the account we had created onboarding apis (action_url and sync) which uses `tracking_id` to track the onboarding progress of a merchant. And the `tracking_id` we are using currently is `connector_id`. We are facing an issue in the connector update flow where the merchant tries the onboarding flow again to signin/signup to a new account. If they don't signup/signin and fetches the current status, the sync api will automatically give the progress of the previous account they have signed in in the create flow. ## Possible solution Instead of using the `connector_id` as the `tracking_id`, we will be use `connector_id_timestamp` as the `tracking_id`. We will create a reset tracking id api which will reset the `tracking_id` by changing the timestamp suffix of the current `tracking_id`. This will be called before the merchant tries to update the mca. As the `tracking_id` is changed in create and update flow, we will no longer get the details of the account which is used in the create flow.
diff --git a/crates/api_models/src/connector_onboarding.rs b/crates/api_models/src/connector_onboarding.rs index 759d3cb97f1..7e8288d9747 100644 --- a/crates/api_models/src/connector_onboarding.rs +++ b/crates/api_models/src/connector_onboarding.rs @@ -52,3 +52,9 @@ pub struct PayPalOnboardingDone { pub struct PayPalIntegrationDone { pub connector_id: String, } + +#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] +pub struct ResetTrackingIdRequest { + pub connector_id: String, + pub connector: enums::Connector, +} diff --git a/crates/api_models/src/events/connector_onboarding.rs b/crates/api_models/src/events/connector_onboarding.rs index 998dc384d62..0da89f61da7 100644 --- a/crates/api_models/src/events/connector_onboarding.rs +++ b/crates/api_models/src/events/connector_onboarding.rs @@ -2,11 +2,13 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::connector_onboarding::{ ActionUrlRequest, ActionUrlResponse, OnboardingStatus, OnboardingSyncRequest, + ResetTrackingIdRequest, }; common_utils::impl_misc_api_event_type!( ActionUrlRequest, ActionUrlResponse, OnboardingSyncRequest, - OnboardingStatus + OnboardingStatus, + ResetTrackingIdRequest ); diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index afe76184630..7b8d6fa0827 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -74,6 +74,9 @@ pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant"; +#[cfg(feature = "olap")] +pub const CONNECTOR_ONBOARDING_CONFIG_PREFIX: &str = "onboarding"; + /// Max payment session expiry pub const MAX_SESSION_EXPIRY: u32 = 7890000; diff --git a/crates/router/src/core/connector_onboarding.rs b/crates/router/src/core/connector_onboarding.rs index e48026edc2d..e6c1fc9d378 100644 --- a/crates/router/src/core/connector_onboarding.rs +++ b/crates/router/src/core/connector_onboarding.rs @@ -1,5 +1,4 @@ use api_models::{connector_onboarding as api, enums}; -use error_stack::ResultExt; use masking::Secret; use crate::{ @@ -19,16 +18,23 @@ pub trait AccessToken { pub async fn get_action_url( state: AppState, + user_from_token: auth::UserFromToken, request: api::ActionUrlRequest, ) -> RouterResponse<api::ActionUrlResponse> { + utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) + .await?; + let connector_onboarding_conf = state.conf.connector_onboarding.clone(); let is_enabled = utils::is_enabled(request.connector, &connector_onboarding_conf); + let tracking_id = + utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector) + .await?; match (is_enabled, request.connector) { (Some(true), enums::Connector::Paypal) => { let action_url = Box::pin(paypal::get_action_url_from_paypal( state, - request.connector_id, + tracking_id, request.return_url, )) .await?; @@ -49,40 +55,42 @@ pub async fn sync_onboarding_status( user_from_token: auth::UserFromToken, request: api::OnboardingSyncRequest, ) -> RouterResponse<api::OnboardingStatus> { - let merchant_account = user_from_token - .get_merchant_account(state.clone()) - .await - .change_context(ApiErrorResponse::MerchantAccountNotFound)?; + utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) + .await?; + let connector_onboarding_conf = state.conf.connector_onboarding.clone(); let is_enabled = utils::is_enabled(request.connector, &connector_onboarding_conf); + let tracking_id = + utils::get_tracking_id_from_configs(&state, &request.connector_id, request.connector) + .await?; match (is_enabled, request.connector) { (Some(true), enums::Connector::Paypal) => { let status = Box::pin(paypal::sync_merchant_onboarding_status( state.clone(), - request.connector_id.clone(), + tracking_id, )) .await?; if let api::OnboardingStatus::PayPal(api::PayPalOnboardingStatus::Success( - ref inner_data, + ref paypal_onboarding_data, )) = status { let connector_onboarding_conf = state.conf.connector_onboarding.clone(); let auth_details = oss_types::ConnectorAuthType::SignatureKey { api_key: connector_onboarding_conf.paypal.client_secret, key1: connector_onboarding_conf.paypal.client_id, - api_secret: Secret::new(inner_data.payer_id.clone()), + api_secret: Secret::new(paypal_onboarding_data.payer_id.clone()), }; - let some_data = paypal::update_mca( + let update_mca_data = paypal::update_mca( &state, - &merchant_account, + user_from_token.merchant_id, request.connector_id.to_owned(), auth_details, ) .await?; return Ok(ApplicationResponse::Json(api::OnboardingStatus::PayPal( - api::PayPalOnboardingStatus::ConnectorIntegrated(some_data), + api::PayPalOnboardingStatus::ConnectorIntegrated(update_mca_data), ))); } Ok(ApplicationResponse::Json(status)) @@ -94,3 +102,15 @@ pub async fn sync_onboarding_status( .into()), } } + +pub async fn reset_tracking_id( + state: AppState, + user_from_token: auth::UserFromToken, + request: api::ResetTrackingIdRequest, +) -> RouterResponse<()> { + utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id) + .await?; + utils::set_tracking_id_in_configs(&state, &request.connector_id, request.connector).await?; + + Ok(ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs index 30aa69067b5..f18681f8cfd 100644 --- a/crates/router/src/core/connector_onboarding/paypal.rs +++ b/crates/router/src/core/connector_onboarding/paypal.rs @@ -23,11 +23,11 @@ fn build_referral_url(state: AppState) -> String { async fn build_referral_request( state: AppState, - connector_id: String, + tracking_id: String, return_url: String, ) -> RouterResult<Request> { let access_token = utils::paypal::generate_access_token(state.clone()).await?; - let request_body = types::paypal::PartnerReferralRequest::new(connector_id, return_url); + let request_body = types::paypal::PartnerReferralRequest::new(tracking_id, return_url); utils::paypal::build_paypal_post_request( build_referral_url(state), @@ -38,12 +38,12 @@ async fn build_referral_request( pub async fn get_action_url_from_paypal( state: AppState, - connector_id: String, + tracking_id: String, return_url: String, ) -> RouterResult<String> { let referral_request = Box::pin(build_referral_request( state.clone(), - connector_id, + tracking_id, return_url, )) .await?; @@ -137,7 +137,7 @@ async fn find_paypal_merchant_by_tracking_id( pub async fn update_mca( state: &AppState, - merchant_account: &oss_types::domain::MerchantAccount, + merchant_id: String, connector_id: String, auth_details: oss_types::ConnectorAuthType, ) -> RouterResult<oss_api_types::MerchantConnectorResponse> { @@ -159,13 +159,9 @@ pub async fn update_mca( connector_webhook_details: None, pm_auth_config: None, }; - let mca_response = admin::update_payment_connector( - state.clone(), - &merchant_account.merchant_id, - &connector_id, - request, - ) - .await?; + let mca_response = + admin::update_payment_connector(state.clone(), &merchant_id, &connector_id, request) + .await?; match mca_response { ApplicationResponse::Json(mca_data) => Ok(mca_data), diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6625a206be2..03e63553a66 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -942,5 +942,6 @@ impl ConnectorOnboarding { .app_data(web::Data::new(state)) .service(web::resource("/action_url").route(web::post().to(get_action_url))) .service(web::resource("/sync").route(web::post().to(sync_onboarding_status))) + .service(web::resource("/reset_tracking_id").route(web::post().to(reset_tracking_id))) } } diff --git a/crates/router/src/routes/connector_onboarding.rs b/crates/router/src/routes/connector_onboarding.rs index b7c39b3c1d2..f5555f5bf9b 100644 --- a/crates/router/src/routes/connector_onboarding.rs +++ b/crates/router/src/routes/connector_onboarding.rs @@ -20,7 +20,7 @@ pub async fn get_action_url( state, &http_req, req_payload.clone(), - |state, _: auth::UserFromToken, req| core::get_action_url(state, req), + core::get_action_url, &auth::JWTAuth(Permission::MerchantAccountWrite), api_locking::LockAction::NotApplicable, )) @@ -45,3 +45,22 @@ pub async fn sync_onboarding_status( )) .await } + +pub async fn reset_tracking_id( + state: web::Data<AppState>, + http_req: HttpRequest, + json_payload: web::Json<api_types::ResetTrackingIdRequest>, +) -> HttpResponse { + let flow = Flow::ResetTrackingId; + let req_payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow.clone(), + state, + &http_req, + req_payload.clone(), + core::reset_tracking_id, + &auth::JWTAuth(Permission::MerchantAccountWrite), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 10f408f3d4f..65d65366013 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -178,7 +178,9 @@ impl From<Flow> for ApiIdentifier { Self::UserRole } - Flow::GetActionUrl | Flow::SyncOnboardingStatus => Self::ConnectorOnboarding, + Flow::GetActionUrl | Flow::SyncOnboardingStatus | Flow::ResetTrackingId => { + Self::ConnectorOnboarding + } } } } diff --git a/crates/router/src/utils/connector_onboarding.rs b/crates/router/src/utils/connector_onboarding.rs index e8afcd68a46..03735e61cc7 100644 --- a/crates/router/src/utils/connector_onboarding.rs +++ b/crates/router/src/utils/connector_onboarding.rs @@ -1,6 +1,11 @@ +use diesel_models::{ConfigNew, ConfigUpdate}; +use error_stack::ResultExt; + +use super::errors::StorageErrorExt; use crate::{ + consts, core::errors::{api_error_response::NotImplementedMessage, ApiErrorResponse, RouterResult}, - routes::app::settings, + routes::{app::settings, AppState}, types::{self, api::enums}, }; @@ -34,3 +39,105 @@ pub fn is_enabled( _ => None, } } + +pub async fn check_if_connector_exists( + state: &AppState, + connector_id: &str, + merchant_id: &str, +) -> RouterResult<()> { + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; + + let _connector = state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + merchant_id, + connector_id, + &key_store, + ) + .await + .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound { + id: connector_id.to_string(), + })?; + + Ok(()) +} + +pub async fn set_tracking_id_in_configs( + state: &AppState, + connector_id: &str, + connector: enums::Connector, +) -> RouterResult<()> { + let timestamp = common_utils::date_time::now_unix_timestamp().to_string(); + let find_config = state + .store + .find_config_by_key(&build_key(connector_id, connector)) + .await; + + if find_config.is_ok() { + state + .store + .update_config_by_key( + &build_key(connector_id, connector), + ConfigUpdate::Update { + config: Some(timestamp), + }, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Error updating data in configs table")?; + } else if find_config + .as_ref() + .map_err(|e| e.current_context().is_db_not_found()) + .err() + .unwrap_or(false) + { + state + .store + .insert_config(ConfigNew { + key: build_key(connector_id, connector), + config: timestamp, + }) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Error inserting data in configs table")?; + } else { + find_config.change_context(ApiErrorResponse::InternalServerError)?; + } + + Ok(()) +} + +pub async fn get_tracking_id_from_configs( + state: &AppState, + connector_id: &str, + connector: enums::Connector, +) -> RouterResult<String> { + let timestamp = state + .store + .find_config_by_key_unwrap_or( + &build_key(connector_id, connector), + Some(common_utils::date_time::now_unix_timestamp().to_string()), + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Error getting data from configs table")? + .config; + + Ok(format!("{}_{}", connector_id, timestamp)) +} + +fn build_key(connector_id: &str, connector: enums::Connector) -> String { + format!( + "{}_{}_{}", + consts::CONNECTOR_ONBOARDING_CONFIG_PREFIX, + connector, + connector_id, + ) +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index e37e15443bd..110402444c5 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -311,6 +311,8 @@ pub enum Flow { GetActionUrl, /// Sync connector onboarding status SyncOnboardingStatus, + /// Reset tracking id + ResetTrackingId, /// Verify email Token VerifyEmail, /// Send verify email
2024-01-03T08:48:26Z
## Description <!-- Describe your changes in detail --> 1. This PR adds checks in connector_onboarding to only proceed if the connector exists for the given merchant_account. 2. Reset tracking id api has been added to connector onboarding, which will reset the tracking details of the onboarded merchant. This can be used to update the process without any interference of previous account. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> 1. To catch any errors without the connector id check beforehand. 2. To make the update flow of connector onboarding better. #
5a1a3da7502ce9e13546b896477d82719162d5b6
Postman. ``` curl --location 'http://localhost:8080/connector_onboarding/action_url' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "connector": "paypal", "connector_id": "", "return_url": "https://google.com" }' ``` ``` curl --location 'http://localhost:8080/connector_onboarding/sync' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "connector": "paypal", "profile_id": "", "connector_id": "" }' ``` If the connector_id is invalid, these apis will throw this error ``` { "error": { "type": "invalid_request", "message": "Merchant connector account does not exist in our records", "code": "HE_02", "reason": " does not exist" } } ``` This api will reset the progress of the onboarding flow. This api will give 200 OK if everything works correctly. ``` curl --location 'http://localhost:8080/connector_onboarding/reset_tracking_id' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "connector_id": "", "connector": "paypal" }' ```
[ "crates/api_models/src/connector_onboarding.rs", "crates/api_models/src/events/connector_onboarding.rs", "crates/router/src/consts.rs", "crates/router/src/core/connector_onboarding.rs", "crates/router/src/core/connector_onboarding/paypal.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/...
juspay/hyperswitch
juspay__hyperswitch-3232
Bug: [BUG]: Recurring Payments via Wallets for Cybersource ### Bug Description Recurring/Subsequent Mandate payments are not working for cyber source when the payment_method is wallets ### Expected Behavior Zero and non-zero, recurring and non-recurring payments should flow for cards and wallets via cyber source ### Actual Behavior Recurring/Subsequent Mandate payments are not working for cyber source when the payment_method is wallets ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/development.toml b/config/development.toml index d365abc4674..6e7e040906a 100644 --- a/config/development.toml +++ b/config/development.toml @@ -468,8 +468,8 @@ connectors_with_webhook_source_verification_call = "paypal" [mandates.supported_payment_methods] pay_later.klarna = { connector_list = "adyen" } -wallet.google_pay = { connector_list = "stripe,adyen" } -wallet.apple_pay = { connector_list = "stripe,adyen" } +wallet.google_pay = { connector_list = "stripe,adyen,cybersource" } +wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" } wallet.paypal = { connector_list = "adyen" } card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } card.debit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" } diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 147e50a9e91..a5a0a7237ef 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -78,7 +78,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { }; let (action_list, action_token_types, authorization_options) = ( Some(vec![CybersourceActionsList::TokenCreate]), - Some(vec![CybersourceActionsTokenType::InstrumentIdentifier]), + Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { initiator: CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), @@ -89,38 +89,122 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { }), ); - let processing_information = ProcessingInformation { - capture: Some(false), - capture_options: None, - action_list, - action_token_types, - authorization_options, - commerce_indicator: CybersourceCommerceIndicator::Internet, - payment_solution: None, - }; - let client_reference_information = ClientReferenceInformation { code: Some(item.connector_request_reference_id.clone()), }; - let payment_information = match item.request.payment_method_data.clone() { + let (payment_information, solution) = match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(ccard) => { - let card = CardDetails::PaymentCard(Card { - number: ccard.card_number, - expiration_month: ccard.card_exp_month, - expiration_year: ccard.card_exp_year, - security_code: ccard.card_cvc, - card_type: None, - }); - PaymentInformation::Cards(CardPaymentInformation { - card, - instrument_identifier: None, - }) + let card_issuer = ccard.get_card_issuer(); + let card_type = match card_issuer { + Ok(issuer) => Some(String::from(issuer)), + Err(_) => None, + }; + ( + PaymentInformation::Cards(CardPaymentInformation { + card: Card { + number: ccard.card_number, + expiration_month: ccard.card_exp_month, + expiration_year: ccard.card_exp_year, + security_code: ccard.card_cvc, + card_type, + }, + }), + None, + ) } + + api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + payments::WalletData::ApplePay(apple_pay_data) => { + match item.payment_method_token.clone() { + Some(payment_method_token) => match payment_method_token { + types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { + let expiration_month = decrypt_data.get_expiry_month()?; + let expiration_year = decrypt_data.get_four_digit_expiry_year()?; + ( + PaymentInformation::ApplePay(ApplePayPaymentInformation { + tokenized_card: TokenizedCard { + number: decrypt_data.application_primary_account_number, + cryptogram: decrypt_data + .payment_data + .online_payment_cryptogram, + transaction_type: TransactionType::ApplePay, + expiration_year, + expiration_month, + }, + }), + Some(PaymentSolution::ApplePay), + ) + } + types::PaymentMethodToken::Token(_) => { + Err(errors::ConnectorError::InvalidWalletToken)? + } + }, + None => ( + PaymentInformation::ApplePayToken(ApplePayTokenPaymentInformation { + fluid_data: FluidData { + value: Secret::from(apple_pay_data.payment_data), + }, + tokenized_card: ApplePayTokenizedCard { + transaction_type: TransactionType::ApplePay, + }, + }), + Some(PaymentSolution::ApplePay), + ), + } + } + payments::WalletData::GooglePay(google_pay_data) => ( + PaymentInformation::GooglePay(GooglePayPaymentInformation { + fluid_data: FluidData { + value: Secret::from( + consts::BASE64_ENGINE + .encode(google_pay_data.tokenization_data.token), + ), + }, + }), + Some(PaymentSolution::GooglePay), + ), + payments::WalletData::AliPayQr(_) + | payments::WalletData::AliPayRedirect(_) + | payments::WalletData::AliPayHkRedirect(_) + | payments::WalletData::MomoRedirect(_) + | payments::WalletData::KakaoPayRedirect(_) + | payments::WalletData::GoPayRedirect(_) + | payments::WalletData::GcashRedirect(_) + | payments::WalletData::ApplePayRedirect(_) + | payments::WalletData::ApplePayThirdPartySdk(_) + | payments::WalletData::DanaRedirect {} + | payments::WalletData::GooglePayRedirect(_) + | payments::WalletData::GooglePayThirdPartySdk(_) + | payments::WalletData::MbWayRedirect(_) + | payments::WalletData::MobilePayRedirect(_) + | payments::WalletData::PaypalRedirect(_) + | payments::WalletData::PaypalSdk(_) + | payments::WalletData::SamsungPay(_) + | payments::WalletData::TwintRedirect {} + | payments::WalletData::VippsRedirect {} + | payments::WalletData::TouchNGoRedirect(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::WeChatPayQr(_) + | payments::WalletData::CashappQr(_) + | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Cybersource"), + ))?, + }, _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ))?, }; + + let processing_information = ProcessingInformation { + capture: Some(false), + capture_options: None, + action_list, + action_token_types, + authorization_options, + commerce_indicator: CybersourceCommerceIndicator::Internet, + payment_solution: solution.map(String::from), + }; Ok(Self { processing_information, payment_information, @@ -169,7 +253,7 @@ pub enum CybersourceActionsList { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub enum CybersourceActionsTokenType { - InstrumentIdentifier, + PaymentInstrument, } #[derive(Debug, Serialize)] @@ -216,8 +300,7 @@ pub struct CaptureOptions { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct CardPaymentInformation { - card: CardDetails, - instrument_identifier: Option<CybersoucreInstrumentIdentifier>, + card: Card, } #[derive(Debug, Serialize)] @@ -249,6 +332,12 @@ pub struct ApplePayPaymentInformation { tokenized_card: TokenizedCard, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MandatePaymentInformation { + payment_instrument: Option<CybersoucrePaymentInstrument>, +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct FluidData { @@ -268,20 +357,13 @@ pub enum PaymentInformation { GooglePay(GooglePayPaymentInformation), ApplePay(ApplePayPaymentInformation), ApplePayToken(ApplePayTokenPaymentInformation), + MandatePayment(MandatePaymentInformation), } #[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CybersoucreInstrumentIdentifier { +pub struct CybersoucrePaymentInstrument { id: String, } - -#[derive(Debug, Serialize)] -#[serde(untagged)] -pub enum CardDetails { - PaymentCard(Card), - MandateCard(MandateCardDetails), -} - #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Card { @@ -292,14 +374,6 @@ pub struct Card { #[serde(rename = "type")] card_type: Option<String>, } - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct MandateCardDetails { - expiration_month: Secret<String>, - expiration_year: Secret<String>, -} - #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationWithBill { @@ -394,7 +468,7 @@ impl if item.router_data.request.setup_future_usage.is_some() { ( Some(vec![CybersourceActionsList::TokenCreate]), - Some(vec![CybersourceActionsTokenType::InstrumentIdentifier]), + Some(vec![CybersourceActionsTokenType::PaymentInstrument]), Some(CybersourceAuthorizationOptions { initiator: CybersourcePaymentInitiator { initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), @@ -507,33 +581,16 @@ impl Err(_) => None, }; - let instrument_identifier = - item.router_data - .request - .connector_mandate_id() - .map(|mandate_token_id| CybersoucreInstrumentIdentifier { - id: mandate_token_id, - }); - - let card = if instrument_identifier.is_some() { - CardDetails::MandateCard(MandateCardDetails { - expiration_month: ccard.card_exp_month, - expiration_year: ccard.card_exp_year, - }) - } else { - CardDetails::PaymentCard(Card { + let payment_information = PaymentInformation::Cards(CardPaymentInformation { + card: Card { number: ccard.card_number, expiration_month: ccard.card_exp_month, expiration_year: ccard.card_exp_year, security_code: ccard.card_cvc, card_type, - }) - }; - - let payment_information = PaymentInformation::Cards(CardPaymentInformation { - card, - instrument_identifier, + }, }); + let processing_information = ProcessingInformation::from((item, None)); let client_reference_information = ClientReferenceInformation::from(item); let merchant_defined_information = @@ -726,13 +783,42 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> ) .into()), }, + payments::PaymentMethodData::MandatePayment => { + let processing_information = ProcessingInformation::from((item, None)); + let payment_instrument = + item.router_data + .request + .connector_mandate_id() + .map(|mandate_token_id| CybersoucrePaymentInstrument { + id: mandate_token_id, + }); + + let email = item.router_data.request.get_email()?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; + let order_information = OrderInformationWithBill::from((item, bill_to)); + let payment_information = + PaymentInformation::MandatePayment(MandatePaymentInformation { + payment_instrument, + }); + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = + item.router_data.request.metadata.clone().map(|metadata| { + Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned()) + }); + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + merchant_defined_information, + }) + } payments::PaymentMethodData::CardRedirect(_) | payments::PaymentMethodData::PayLater(_) | payments::PaymentMethodData::BankRedirect(_) | payments::PaymentMethodData::BankDebit(_) | payments::PaymentMethodData::BankTransfer(_) | payments::PaymentMethodData::Crypto(_) - | payments::PaymentMethodData::MandatePayment | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) @@ -1019,14 +1105,11 @@ pub struct CybersourcePaymentsIncrementalAuthorizationResponse { error_information: Option<CybersourceErrorInformation>, } -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct CybersourceSetupMandatesResponse { - id: String, - status: CybersourcePaymentStatus, - error_information: Option<CybersourceErrorInformation>, - client_reference_information: Option<ClientReferenceInformation>, - token_information: Option<CybersourceTokenInformation>, +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum CybersourceSetupMandatesResponse { + ClientReferenceInformation(CybersourceClientReferenceResponse), + ErrorInformation(CybersourceErrorInformationResponse), } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1038,7 +1121,7 @@ pub struct ClientReferenceInformation { #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CybersourceTokenInformation { - instrument_identifier: CybersoucreInstrumentIdentifier, + payment_instrument: CybersoucrePaymentInstrument, } #[derive(Debug, Clone, Deserialize)] @@ -1161,7 +1244,7 @@ fn get_payment_response( .token_information .clone() .map(|token_info| types::MandateReference { - connector_mandate_id: Some(token_info.instrument_identifier.id), + connector_mandate_id: Some(token_info.payment_instrument.id), payment_method_id: None, }); Ok(types::PaymentsResponseData::TransactionResponse { @@ -1327,51 +1410,66 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let mandate_reference = - item.response - .token_information - .map(|token_info| types::MandateReference { - connector_mandate_id: Some(token_info.instrument_identifier.id), - payment_method_id: None, + match item.response { + CybersourceSetupMandatesResponse::ClientReferenceInformation(info_response) => { + let mandate_reference = info_response.token_information.clone().map(|token_info| { + types::MandateReference { + connector_mandate_id: Some(token_info.payment_instrument.id), + payment_method_id: None, + } }); - let mut mandate_status = enums::AttemptStatus::foreign_from((item.response.status, false)); - if matches!(mandate_status, enums::AttemptStatus::Authorized) { - //In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well. - mandate_status = enums::AttemptStatus::Charged - } - Ok(Self { - status: mandate_status, - response: match item.response.error_information { - Some(error) => Err(types::ErrorResponse { + let mut mandate_status = + enums::AttemptStatus::foreign_from((info_response.status.clone(), false)); + if matches!(mandate_status, enums::AttemptStatus::Authorized) { + //In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well. + mandate_status = enums::AttemptStatus::Charged + } + let error_response = + get_error_response_if_failure((&info_response, mandate_status, item.http_code)); + + Ok(Self { + status: mandate_status, + response: match error_response { + Some(error) => Err(error), + None => Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + info_response.id.clone(), + ), + redirection_data: None, + mandate_reference, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .clone() + .unwrap_or(info_response.id), + ), + incremental_authorization_allowed: Some( + mandate_status == enums::AttemptStatus::Authorized, + ), + }), + }, + ..item.data + }) + } + CybersourceSetupMandatesResponse::ErrorInformation(error_response) => Ok(Self { + response: Err(types::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), - message: error + message: error_response + .error_information .message .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), - reason: error.reason, + reason: error_response.error_information.reason, status_code: item.http_code, attempt_status: None, - connector_transaction_id: Some(item.response.id), - }), - _ => Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.id.clone(), - ), - redirection_data: None, - mandate_reference, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: item - .response - .client_reference_information - .map(|cref| cref.code) - .unwrap_or(Some(item.response.id)), - incremental_authorization_allowed: Some( - mandate_status == enums::AttemptStatus::Authorized, - ), + connector_transaction_id: Some(error_response.id.clone()), }), - }, - ..item.data - }) + status: enums::AttemptStatus::Failure, + ..item.data + }), + } } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index bfd747640d3..aed22eaedc8 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1770,24 +1770,10 @@ where .unwrap_or(false); let payment_data_and_tokenization_action = match connector { - Some(connector_name) if is_mandate => { - if connector_name == *"cybersource" { - let (_operation, payment_method_data) = operation - .to_domain()? - .make_pm_data( - state, - payment_data, - validate_result.storage_scheme, - merchant_key_store, - ) - .await?; - payment_data.payment_method_data = payment_method_data; - } - ( - payment_data.to_owned(), - TokenizationAction::SkipConnectorTokenization, - ) - } + Some(_) if is_mandate => ( + payment_data.to_owned(), + TokenizationAction::SkipConnectorTokenization, + ), Some(connector) if is_operation_confirm(&operation) => { let payment_method = &payment_data .payment_attempt @@ -1870,7 +1856,7 @@ where }; (payment_data.to_owned(), connector_tokenization_action) } - Some(_) | None => ( + _ => ( payment_data.to_owned(), TokenizationAction::SkipConnectorTokenization, ),
2024-01-02T13:07:27Z
## Description - [fix]: Recurring Payments via Wallets - [feat]: Implement zero dollar mandates and recurring payments via wallets - [refactor]: Update the mandate token created with cybersource from `instrumentIdentifier` to `PaymentInstrument` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
e06ba148b666772fe79d7050d0c505dd2f04f87c
- Create a Merchant and an Mca for cyberource - Make a setup mandate payment for card and also for wallet - Make a recurring mandate payment for card and also google_pay - The payment should succeed - Test both zero and non-zero mandate creation <img width="1177" alt="Screenshot 2024-01-03 at 4 50 42 PM" src="https://github.com/juspay/hyperswitch/assets/55536657/fa2db15d-2aea-43fe-a80a-18772facc124">
[ "config/development.toml", "crates/router/src/connector/cybersource/transformers.rs", "crates/router/src/core/payments.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3190
Bug: [FEATURE] Replace Routing cache with Moka ### Feature Description Have to replace static routing cache with moka cache in order to use extra features like TTL ### Possible Implementation Just need to replace the current cache. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 4c2ebb516e6..b50c5b69681 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1245,17 +1245,6 @@ pub async fn update_payment_connector( } } - // The purpose of this merchant account update is just to update the - // merchant account `modified_at` field for KGraph cache invalidation - db.update_specific_fields_in_merchant( - merchant_id, - storage::MerchantAccountUpdate::ModifiedAtUpdate, - &key_store, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("error updating the merchant account when updating payment connector")?; - let payment_connector = storage::MerchantConnectorAccountUpdate::Update { merchant_id: None, connector_type: Some(req.connector_type), diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ff48d181a77..175400c54bf 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3192,7 +3192,6 @@ where connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &TransactionData::Payment(payment_data), eligible_connectors, @@ -3250,7 +3249,6 @@ where connectors = routing::perform_eligibility_analysis_with_fallback( &state, key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &TransactionData::Payment(payment_data), eligible_connectors, @@ -3680,7 +3678,6 @@ where let connectors = routing::perform_eligibility_analysis_with_fallback( &state.clone(), key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &transaction_data, eligible_connectors, diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 802ba524cc6..d45f804268b 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -13,7 +13,6 @@ use api_models::{ payments::Address, routing::ConnectorSelection, }; -use common_utils::static_cache::StaticCache; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ @@ -33,6 +32,7 @@ use rand::{ SeedableRng, }; use rustc_hash::FxHashMap; +use storage_impl::redis::cache::{CGRAPH_CACHE, ROUTING_CACHE}; #[cfg(feature = "payouts")] use crate::core::payouts; @@ -53,7 +53,7 @@ use crate::{ AppState, }; -pub(super) enum CachedAlgorithm { +pub enum CachedAlgorithm { Single(Box<routing_types::RoutableConnectorChoice>), Priority(Vec<routing_types::RoutableConnectorChoice>), VolumeSplit(Vec<routing_types::ConnectorVolumeSplit>), @@ -73,7 +73,6 @@ pub struct SessionFlowRoutingInput<'a> { pub struct SessionRoutingPmTypeInput<'a> { state: &'a AppState, key_store: &'a domain::MerchantKeyStore, - merchant_last_modified: i64, attempt_id: &'a str, routing_algorithm: &'a MerchantAccountRoutingAlgorithm, backend_input: dsl_inputs::BackendInput, @@ -84,10 +83,6 @@ pub struct SessionRoutingPmTypeInput<'a> { ))] profile_id: Option<String>, } -static ROUTING_CACHE: StaticCache<CachedAlgorithm> = StaticCache::new(); -static KGRAPH_CACHE: StaticCache< - hyperswitch_constraint_graph::ConstraintGraph<'_, euclid_dir::DirValue>, -> = StaticCache::new(); type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>; @@ -302,20 +297,15 @@ pub async fn perform_static_routing_v1<F: Clone>( return Ok(fallback_config); }; - let key = ensure_algorithm_cached_v1( + let cached_algorithm = ensure_algorithm_cached_v1( state, merchant_id, - algorithm_ref.timestamp, &algorithm_id, #[cfg(feature = "business_profile_routing")] Some(profile_id).cloned(), &api_enums::TransactionType::from(transaction_data), ) .await?; - let cached_algorithm: Arc<CachedAlgorithm> = ROUTING_CACHE - .retrieve(&key) - .change_context(errors::RoutingError::CacheMiss) - .attach_printable("Unable to retrieve cached routing algorithm even after refresh")?; Ok(match cached_algorithm.as_ref() { CachedAlgorithm::Single(conn) => vec![(**conn).clone()], @@ -342,11 +332,10 @@ pub async fn perform_static_routing_v1<F: Clone>( async fn ensure_algorithm_cached_v1( state: &AppState, merchant_id: &str, - timestamp: i64, algorithm_id: &str, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<String> { +) -> RoutingResult<Arc<CachedAlgorithm>> { #[cfg(feature = "business_profile_routing")] let key = { let profile_id = profile_id @@ -376,29 +365,24 @@ async fn ensure_algorithm_cached_v1( } }; - let present = ROUTING_CACHE - .present(&key) - .change_context(errors::RoutingError::DslCachePoisoned) - .attach_printable("Error checking presence of DSL")?; + let cached_algorithm = ROUTING_CACHE + .get_val::<Arc<CachedAlgorithm>>(key.as_str()) + .await; - let expired = ROUTING_CACHE - .expired(&key, timestamp) - .change_context(errors::RoutingError::DslCachePoisoned) - .attach_printable("Error checking expiry of DSL in cache")?; - - if !present || expired { + let algorithm = if let Some(algo) = cached_algorithm { + algo + } else { refresh_routing_cache_v1( state, key.clone(), algorithm_id, - timestamp, #[cfg(feature = "business_profile_routing")] profile_id, ) - .await?; + .await? }; - Ok(key) + Ok(algorithm) } pub fn perform_straight_through_routing( @@ -447,9 +431,8 @@ pub async fn refresh_routing_cache_v1( state: &AppState, key: String, algorithm_id: &str, - timestamp: i64, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, -) -> RoutingResult<()> { +) -> RoutingResult<Arc<CachedAlgorithm>> { #[cfg(feature = "business_profile_routing")] let algorithm = { let algorithm = state @@ -498,12 +481,11 @@ pub async fn refresh_routing_cache_v1( } }; - ROUTING_CACHE - .save(key, cached_algorithm, timestamp) - .change_context(errors::RoutingError::DslCachePoisoned) - .attach_printable("Error saving DSL to cache")?; + let arc_cached_algorithm = Arc::new(cached_algorithm); + + ROUTING_CACHE.push(key, arc_cached_algorithm.clone()).await; - Ok(()) + Ok(arc_cached_algorithm) } pub fn perform_volume_split( @@ -540,10 +522,9 @@ pub fn perform_volume_split( Ok(splits.into_iter().map(|sp| sp.connector).collect()) } -pub async fn get_merchant_kgraph<'a>( +pub async fn get_merchant_cgraph<'a>( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, transaction_type: &api_enums::TransactionType, ) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<'a, euclid_dir::DirValue>>> { @@ -556,10 +537,10 @@ pub async fn get_merchant_kgraph<'a>( .get_required_value("profile_id") .change_context(errors::RoutingError::ProfileIdMissing)?; match transaction_type { - api_enums::TransactionType::Payment => format!("kgraph_{}_{}", merchant_id, profile_id), + api_enums::TransactionType::Payment => format!("cgraph_{}_{}", merchant_id, profile_id), #[cfg(feature = "payouts")] api_enums::TransactionType::Payout => { - format!("kgraph_po_{}_{}", merchant_id, profile_id) + format!("cgraph_po_{}_{}", merchant_id, profile_id) } } }; @@ -571,45 +552,36 @@ pub async fn get_merchant_kgraph<'a>( api_enums::TransactionType::Payout => format!("kgraph_po_{}", merchant_id), }; - let kgraph_present = KGRAPH_CACHE - .present(&key) - .change_context(errors::RoutingError::KgraphCacheFailure) - .attach_printable("when checking kgraph presence")?; - - let kgraph_expired = KGRAPH_CACHE - .expired(&key, merchant_last_modified) - .change_context(errors::RoutingError::KgraphCacheFailure) - .attach_printable("when checking kgraph expiry")?; + let cached_cgraph = CGRAPH_CACHE + .get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<'_, euclid_dir::DirValue>>>( + key.as_str(), + ) + .await; - if !kgraph_present || kgraph_expired { - refresh_kgraph_cache( + let cgraph = if let Some(graph) = cached_cgraph { + graph + } else { + refresh_cgraph_cache( state, key_store, - merchant_last_modified, key.clone(), #[cfg(feature = "business_profile_routing")] profile_id, transaction_type, ) - .await?; - } - - let cached_kgraph = KGRAPH_CACHE - .retrieve(&key) - .change_context(errors::RoutingError::CacheMiss) - .attach_printable("when retrieving kgraph")?; + .await? + }; - Ok(cached_kgraph) + Ok(cgraph) } -pub async fn refresh_kgraph_cache( +pub async fn refresh_cgraph_cache<'a>( state: &AppState, key_store: &domain::MerchantKeyStore, - timestamp: i64, key: String, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<()> { +) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<'a, euclid_dir::DirValue>>> { let mut merchant_connector_accounts = state .store .find_merchant_connector_account_by_merchant_id_and_disabled_list( @@ -672,23 +644,21 @@ pub async fn refresh_kgraph_cache( connector_configs, default_configs, }; - let kgraph = mca_graph::make_mca_graph(api_mcas, &config_pm_filters) - .change_context(errors::RoutingError::KgraphCacheRefreshFailed) - .attach_printable("when construction kgraph")?; + let cgraph = Arc::new( + mca_graph::make_mca_graph(api_mcas, &config_pm_filters) + .change_context(errors::RoutingError::KgraphCacheRefreshFailed) + .attach_printable("when construction cgraph")?, + ); - KGRAPH_CACHE - .save(key, kgraph, timestamp) - .change_context(errors::RoutingError::KgraphCacheRefreshFailed) - .attach_printable("when saving kgraph to cache")?; + CGRAPH_CACHE.push(key, Arc::clone(&cgraph)).await; - Ok(()) + Ok(cgraph) } #[allow(clippy::too_many_arguments)] -async fn perform_kgraph_filtering( +async fn perform_cgraph_filtering( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, chosen: Vec<routing_types::RoutableConnectorChoice>, backend_input: dsl_inputs::BackendInput, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, @@ -700,10 +670,9 @@ async fn perform_kgraph_filtering( .into_context() .change_context(errors::RoutingError::KgraphAnalysisError)?, ); - let cached_kgraph = get_merchant_kgraph( + let cached_cgraph = get_merchant_cgraph( state, key_store, - merchant_last_modified, #[cfg(feature = "business_profile_routing")] profile_id, transaction_type, @@ -717,7 +686,7 @@ async fn perform_kgraph_filtering( let dir_val = euclid_choice .into_dir_value() .change_context(errors::RoutingError::KgraphAnalysisError)?; - let kgraph_eligible = cached_kgraph + let cgraph_eligible = cached_cgraph .check_value_validity( dir_val, &context, @@ -730,7 +699,7 @@ async fn perform_kgraph_filtering( let filter_eligible = eligible_connectors.map_or(true, |list| list.contains(&routable_connector)); - if kgraph_eligible && filter_eligible { + if cgraph_eligible && filter_eligible { final_selection.push(choice); } } @@ -741,7 +710,6 @@ async fn perform_kgraph_filtering( pub async fn perform_eligibility_analysis<F: Clone>( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, chosen: Vec<routing_types::RoutableConnectorChoice>, transaction_data: &routing::TransactionData<'_, F>, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, @@ -753,10 +721,9 @@ pub async fn perform_eligibility_analysis<F: Clone>( routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?, }; - perform_kgraph_filtering( + perform_cgraph_filtering( state, key_store, - merchant_last_modified, chosen, backend_input, eligible_connectors, @@ -770,7 +737,6 @@ pub async fn perform_eligibility_analysis<F: Clone>( pub async fn perform_fallback_routing<F: Clone>( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, transaction_data: &routing::TransactionData<'_, F>, eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, @@ -801,10 +767,9 @@ pub async fn perform_fallback_routing<F: Clone>( routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?, }; - perform_kgraph_filtering( + perform_cgraph_filtering( state, key_store, - merchant_last_modified, fallback_config, backend_input, eligible_connectors, @@ -818,7 +783,6 @@ pub async fn perform_fallback_routing<F: Clone>( pub async fn perform_eligibility_analysis_with_fallback<F: Clone>( state: &AppState, key_store: &domain::MerchantKeyStore, - merchant_last_modified: i64, chosen: Vec<routing_types::RoutableConnectorChoice>, transaction_data: &routing::TransactionData<'_, F>, eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>, @@ -827,7 +791,6 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>( let mut final_selection = perform_eligibility_analysis( state, key_store, - merchant_last_modified, chosen, transaction_data, eligible_connectors.as_ref(), @@ -839,7 +802,6 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>( let fallback_selection = perform_fallback_routing( state, key_store, - merchant_last_modified, transaction_data, eligible_connectors.as_ref(), #[cfg(feature = "business_profile_routing")] @@ -873,11 +835,6 @@ pub async fn perform_session_flow_routing( ) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice>> { let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> = FxHashMap::default(); - let merchant_last_modified = session_input - .merchant_account - .modified_at - .assume_utc() - .unix_timestamp(); #[cfg(feature = "business_profile_routing")] let routing_algorithm: MerchantAccountRoutingAlgorithm = { @@ -995,7 +952,6 @@ pub async fn perform_session_flow_routing( let session_pm_input = SessionRoutingPmTypeInput { state: session_input.state, key_store: session_input.key_store, - merchant_last_modified, attempt_id: &session_input.payment_attempt.attempt_id, routing_algorithm: &routing_algorithm, backend_input: backend_input.clone(), @@ -1035,10 +991,9 @@ async fn perform_session_routing_for_pm_type( let chosen_connectors = match session_pm_input.routing_algorithm { MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => { if let Some(ref algorithm_id) = algorithm_ref.algorithm_id { - let key = ensure_algorithm_cached_v1( + let cached_algorithm = ensure_algorithm_cached_v1( &session_pm_input.state.clone(), merchant_id, - algorithm_ref.timestamp, algorithm_id, #[cfg(feature = "business_profile_routing")] session_pm_input.profile_id.clone(), @@ -1046,11 +1001,6 @@ async fn perform_session_routing_for_pm_type( ) .await?; - let cached_algorithm = ROUTING_CACHE - .retrieve(&key) - .change_context(errors::RoutingError::CacheMiss) - .attach_printable("unable to retrieve cached routing algorithm")?; - match cached_algorithm.as_ref() { CachedAlgorithm::Single(conn) => vec![(**conn).clone()], CachedAlgorithm::Priority(plist) => plist.clone(), @@ -1084,10 +1034,9 @@ async fn perform_session_routing_for_pm_type( } }; - let mut final_selection = perform_kgraph_filtering( + let mut final_selection = perform_cgraph_filtering( &session_pm_input.state.clone(), session_pm_input.key_store, - session_pm_input.merchant_last_modified, chosen_connectors, session_pm_input.backend_input.clone(), None, @@ -1115,10 +1064,9 @@ async fn perform_session_routing_for_pm_type( .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; - final_selection = perform_kgraph_filtering( + final_selection = perform_cgraph_filtering( &session_pm_input.state.clone(), session_pm_input.key_store, - session_pm_input.merchant_last_modified, fallback, session_pm_input.backend_input, None, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 46c3c8c9aab..dad0739879f 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -669,7 +669,6 @@ pub async fn decide_payout_connector( connectors = routing::perform_eligibility_analysis_with_fallback( state, key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &TransactionData::<()>::Payout(payout_data), eligible_connectors, @@ -728,7 +727,6 @@ pub async fn decide_payout_connector( connectors = routing::perform_eligibility_analysis_with_fallback( state, key_store, - merchant_account.modified_at.assume_utc().unix_timestamp(), connectors, &TransactionData::<()>::Payout(payout_data), eligible_connectors, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 894e09ab60e..1d46e54bccf 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -10,10 +10,11 @@ use diesel_models::{ }; use error_stack::ResultExt; use rustc_hash::FxHashSet; +use storage_impl::redis::cache as redis_cache; use crate::{ core::errors::{self, RouterResult}, - db::StorageInterface, + db::{cache, StorageInterface}, types::{domain, storage}, utils::StringExt, }; @@ -239,6 +240,17 @@ pub async fn update_business_profile_active_algorithm_ref( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert routing ref to value")?; + let merchant_id = current_business_profile.merchant_id.clone(); + + #[cfg(feature = "business_profile_routing")] + let profile_id = current_business_profile.profile_id.clone(); + #[cfg(feature = "business_profile_routing")] + let routing_cache_key = redis_cache::CacheKind::Routing( + format!("routing_config_{merchant_id}_{profile_id}").into(), + ); + + #[cfg(not(feature = "business_profile_routing"))] + let routing_cache_key = redis_cache::CacheKind::Routing(format!("dsl_{merchant_id}").into()); let (routing_algorithm, payout_routing_algorithm) = match transaction_type { storage::enums::TransactionType::Payment => (Some(ref_val), None), #[cfg(feature = "payouts")] @@ -272,6 +284,11 @@ pub async fn update_business_profile_active_algorithm_ref( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref in business profile")?; + + cache::publish_into_redact_channel(db, [routing_cache_key]) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to invalidate routing cache")?; Ok(()) } diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index c323ca4abb1..0cecb5e8d76 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -513,11 +513,29 @@ async fn publish_and_redact_merchant_account_cache( .as_ref() .map(|publishable_key| CacheKind::Accounts(publishable_key.into())); + #[cfg(feature = "business_profile_routing")] + let kgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { + CacheKind::CGraph( + format!( + "kgraph_{}_{}", + merchant_account.merchant_id.clone(), + profile_id, + ) + .into(), + ) + }); + + #[cfg(not(feature = "business_profile_routing"))] + let kgraph_key = Some(CacheKind::CGraph( + format!("kgraph_{}", merchant_account.merchant_id.clone()).into(), + )); + let mut cache_keys = vec![CacheKind::Accounts( merchant_account.merchant_id.as_str().into(), )]; cache_keys.extend(publishable_key.into_iter()); + cache_keys.extend(kgraph_key.into_iter()); super::cache::publish_into_redact_channel(store, cache_keys).await?; Ok(()) diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index 8f50f5f5426..31d965c8cd6 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -427,6 +427,9 @@ impl MerchantConnectorAccountInterface for Store { cache::CacheKind::Accounts( format!("{}_{}", _merchant_id, _merchant_connector_id).into(), ), + cache::CacheKind::CGraph( + format!("cgraph_{}_{_profile_id}", _merchant_id).into(), + ), ], update_call, ) @@ -475,9 +478,16 @@ impl MerchantConnectorAccountInterface for Store { "profile_id".to_string(), ))?; - super::cache::publish_and_redact( + super::cache::publish_and_redact_multiple( self, - cache::CacheKind::Accounts(format!("{}_{}", mca.merchant_id, _profile_id).into()), + [ + cache::CacheKind::Accounts( + format!("{}_{}", mca.merchant_id, _profile_id).into(), + ), + cache::CacheKind::CGraph( + format!("cgraph_{}_{_profile_id}", mca.merchant_id).into(), + ), + ], delete_call, ) .await diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 4cd2fc0c504..80a6847e376 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -21,6 +21,12 @@ const CONFIG_CACHE_PREFIX: &str = "config"; /// Prefix for accounts cache key const ACCOUNTS_CACHE_PREFIX: &str = "accounts"; +/// Prefix for routing cache key +const ROUTING_CACHE_PREFIX: &str = "routing"; + +/// Prefix for kgraph cache key +const CGRAPH_CACHE_PREFIX: &str = "cgraph"; + /// Prefix for all kinds of cache key const ALL_CACHE_PREFIX: &str = "all_cache_kind"; @@ -40,6 +46,14 @@ pub static CONFIG_CACHE: Lazy<Cache> = Lazy::new(|| Cache::new(CACHE_TTL, CACHE_ pub static ACCOUNTS_CACHE: Lazy<Cache> = Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); +/// Routing Cache +pub static ROUTING_CACHE: Lazy<Cache> = + Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); + +/// CGraph Cache +pub static CGRAPH_CACHE: Lazy<Cache> = + Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY))); + /// Trait which defines the behaviour of types that's gonna be stored in Cache pub trait Cacheable: Any + Send + Sync + DynClone { fn as_any(&self) -> &dyn Any; @@ -48,6 +62,8 @@ pub trait Cacheable: Any + Send + Sync + DynClone { pub enum CacheKind<'a> { Config(Cow<'a, str>), Accounts(Cow<'a, str>), + Routing(Cow<'a, str>), + CGraph(Cow<'a, str>), All(Cow<'a, str>), } @@ -56,6 +72,8 @@ impl<'a> From<CacheKind<'a>> for RedisValue { let value = match kind { CacheKind::Config(s) => format!("{CONFIG_CACHE_PREFIX},{s}"), CacheKind::Accounts(s) => format!("{ACCOUNTS_CACHE_PREFIX},{s}"), + CacheKind::Routing(s) => format!("{ROUTING_CACHE_PREFIX},{s}"), + CacheKind::CGraph(s) => format!("{CGRAPH_CACHE_PREFIX},{s}"), CacheKind::All(s) => format!("{ALL_CACHE_PREFIX},{s}"), }; Self::from_string(value) @@ -73,6 +91,8 @@ impl<'a> TryFrom<RedisValue> for CacheKind<'a> { match split.0 { ACCOUNTS_CACHE_PREFIX => Ok(Self::Accounts(Cow::Owned(split.1.to_string()))), CONFIG_CACHE_PREFIX => Ok(Self::Config(Cow::Owned(split.1.to_string()))), + ROUTING_CACHE_PREFIX => Ok(Self::Routing(Cow::Owned(split.1.to_string()))), + CGRAPH_CACHE_PREFIX => Ok(Self::CGraph(Cow::Owned(split.1.to_string()))), ALL_CACHE_PREFIX => Ok(Self::All(Cow::Owned(split.1.to_string()))), _ => Err(validation_err.into()), } @@ -123,6 +143,11 @@ impl Cache { (*val).as_any().downcast_ref::<T>().cloned() } + /// Check if a key exists in cache + pub async fn exists(&self, key: &str) -> bool { + self.inner.contains_key(key) + } + pub async fn remove(&self, key: &str) { self.inner.invalidate(key).await; } diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs index 2922dbcadba..9669e826663 100644 --- a/crates/storage_impl/src/redis/pub_sub.rs +++ b/crates/storage_impl/src/redis/pub_sub.rs @@ -2,7 +2,7 @@ use error_stack::ResultExt; use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue}; use router_env::logger; -use crate::redis::cache::{CacheKind, ACCOUNTS_CACHE, CONFIG_CACHE}; +use crate::redis::cache::{CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, ROUTING_CACHE}; #[async_trait::async_trait] pub trait PubSubInterface { @@ -67,9 +67,19 @@ impl PubSubInterface for redis_interface::RedisConnectionPool { ACCOUNTS_CACHE.remove(key.as_ref()).await; key } + CacheKind::CGraph(key) => { + CGRAPH_CACHE.remove(key.as_ref()).await; + key + } + CacheKind::Routing(key) => { + ROUTING_CACHE.remove(key.as_ref()).await; + key + } CacheKind::All(key) => { CONFIG_CACHE.remove(key.as_ref()).await; ACCOUNTS_CACHE.remove(key.as_ref()).await; + CGRAPH_CACHE.remove(key.as_ref()).await; + ROUTING_CACHE.remove(key.as_ref()).await; key } };
2023-12-28T12:48:19Z
## Description <!-- Describe your changes in detail --> Enabled Moka cache for routing with cache invalidation ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
1523311c479f2caa564b853e668fd47579c2b21f
Look for the pub-sub cache invalidation log ![image](https://github.com/juspay/hyperswitch/assets/76486416/e739ac71-2b2b-4103-9804-b4478c5d0e87) ![image](https://github.com/juspay/hyperswitch/assets/76486416/068743c0-a9d0-49af-859d-f23ab32eb2ec) 1. Update an existing Merchant connector account and look for Cgrpah cache invalidation log ``` curl --location --request POST 'http://localhost:8080/account/sarthak/connectors/mca_VaZpO5COiFDUIiMq7DFV' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "metadata": { "city": "NY", "unit": "248" } }' ``` 2. Activate a routing config from dashboard, then search for routing cache invalidation using routing config key
[ "crates/router/src/core/admin.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/core/payouts/helpers.rs", "crates/router/src/core/routing/helpers.rs", "crates/router/src/db/merchant_account.rs", "crates/router/src/db/merchant_connector_account.rs...
juspay/hyperswitch
juspay__hyperswitch-3267
Bug: Deep health check for Hyperswitch Server Components to be verified in the check: - [x] RDS (PostgreSQL) - Connection to Database - Read check - Write check (v2) - State of Migration (v2) - [x] ElastiCache (Redis) - Connection to Redis - Stream insertions - [x] Locker Connection (/health (deep health check)) - [x] #3518 - Verifying how the pod is able to connect to internet - [x] Clickhouse
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs new file mode 100644 index 00000000000..d7bb120d017 --- /dev/null +++ b/crates/api_models/src/health_check.rs @@ -0,0 +1,6 @@ +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct RouterHealthCheckResponse { + pub database: String, + pub redis: String, + pub locker: String, +} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 935944cf74c..459443747e3 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -16,6 +16,7 @@ pub mod errors; pub mod events; pub mod files; pub mod gsm; +pub mod health_check; pub mod locker_migration; pub mod mandates; pub mod organization; diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 4a2d2831d10..eff42c0cd7c 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -70,3 +70,5 @@ pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant"; + +pub const LOCKER_HEALTH_CALL_PATH: &str = "/health"; diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 0cd4cb21881..5beace9cbb8 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -14,6 +14,7 @@ pub mod events; pub mod file; pub mod fraud_check; pub mod gsm; +pub mod health_check; mod kafka_store; pub mod locker_mock_up; pub mod mandate; @@ -103,6 +104,7 @@ pub trait StorageInterface: + user_role::UserRoleInterface + authorization::AuthorizationInterface + user::sample_data::BatchSampleDataInterface + + health_check::HealthCheckInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/health_check.rs b/crates/router/src/db/health_check.rs new file mode 100644 index 00000000000..73bc2a4321d --- /dev/null +++ b/crates/router/src/db/health_check.rs @@ -0,0 +1,147 @@ +use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; +use diesel_models::ConfigNew; +use error_stack::ResultExt; +use router_env::logger; + +use super::{MockDb, StorageInterface, Store}; +use crate::{ + connection, + consts::LOCKER_HEALTH_CALL_PATH, + core::errors::{self, CustomResult}, + routes, + services::api as services, + types::storage, +}; + +#[async_trait::async_trait] +pub trait HealthCheckInterface { + async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>; + async fn health_check_redis( + &self, + db: &dyn StorageInterface, + ) -> CustomResult<(), errors::HealthCheckRedisError>; + async fn health_check_locker( + &self, + state: &routes::AppState, + ) -> CustomResult<(), errors::HealthCheckLockerError>; +} + +#[async_trait::async_trait] +impl HealthCheckInterface for Store { + async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { + let conn = connection::pg_connection_write(self) + .await + .change_context(errors::HealthCheckDBError::DBError)?; + + let _data = conn + .transaction_async(|conn| { + Box::pin(async move { + let query = + diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1")); + let _x: i32 = query.get_result_async(&conn).await.map_err(|err| { + logger::error!(read_err=?err,"Error while reading element in the database"); + errors::HealthCheckDBError::DBReadError + })?; + + logger::debug!("Database read was successful"); + + let config = ConfigNew { + key: "test_key".to_string(), + config: "test_value".to_string(), + }; + + config.insert(&conn).await.map_err(|err| { + logger::error!(write_err=?err,"Error while writing to database"); + errors::HealthCheckDBError::DBWriteError + })?; + + logger::debug!("Database write was successful"); + + storage::Config::delete_by_key(&conn, "test_key").await.map_err(|err| { + logger::error!(delete_err=?err,"Error while deleting element in the database"); + errors::HealthCheckDBError::DBDeleteError + })?; + + logger::debug!("Database delete was successful"); + + Ok::<_, errors::HealthCheckDBError>(()) + }) + }) + .await?; + + Ok(()) + } + + async fn health_check_redis( + &self, + db: &dyn StorageInterface, + ) -> CustomResult<(), errors::HealthCheckRedisError> { + let redis_conn = db + .get_redis_conn() + .change_context(errors::HealthCheckRedisError::RedisConnectionError)?; + + redis_conn + .serialize_and_set_key_with_expiry("test_key", "test_value", 30) + .await + .change_context(errors::HealthCheckRedisError::SetFailed)?; + + logger::debug!("Redis set_key was successful"); + + redis_conn + .get_key("test_key") + .await + .change_context(errors::HealthCheckRedisError::GetFailed)?; + + logger::debug!("Redis get_key was successful"); + + redis_conn + .delete_key("test_key") + .await + .change_context(errors::HealthCheckRedisError::DeleteFailed)?; + + logger::debug!("Redis delete_key was successful"); + + Ok(()) + } + + async fn health_check_locker( + &self, + state: &routes::AppState, + ) -> CustomResult<(), errors::HealthCheckLockerError> { + let locker = &state.conf.locker; + if !locker.mock_locker { + let mut url = locker.host_rs.to_owned(); + url.push_str(LOCKER_HEALTH_CALL_PATH); + let request = services::Request::new(services::Method::Get, &url); + services::call_connector_api(state, request) + .await + .change_context(errors::HealthCheckLockerError::FailedToCallLocker)? + .ok(); + } + + logger::debug!("Locker call was successful"); + + Ok(()) + } +} + +#[async_trait::async_trait] +impl HealthCheckInterface for MockDb { + async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { + Ok(()) + } + + async fn health_check_redis( + &self, + _: &dyn StorageInterface, + ) -> CustomResult<(), errors::HealthCheckRedisError> { + Ok(()) + } + + async fn health_check_locker( + &self, + _: &routes::AppState, + ) -> CustomResult<(), errors::HealthCheckLockerError> { + Ok(()) + } +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index db94c1bcbca..1184992a8f7 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -43,6 +43,7 @@ use crate::{ events::EventInterface, file::FileMetadataInterface, gsm::GsmInterface, + health_check::HealthCheckInterface, locker_mock_up::LockerMockUpInterface, mandate::MandateInterface, merchant_account::MerchantAccountInterface, @@ -57,6 +58,7 @@ use crate::{ routing_algorithm::RoutingAlgorithmInterface, MasterKeyInterface, StorageInterface, }, + routes, services::{authentication, kafka::KafkaProducer, Store}, types::{ domain, @@ -2131,3 +2133,24 @@ impl AuthorizationInterface for KafkaStore { .await } } + +#[async_trait::async_trait] +impl HealthCheckInterface for KafkaStore { + async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { + self.diesel_store.health_check_db().await + } + + async fn health_check_redis( + &self, + db: &dyn StorageInterface, + ) -> CustomResult<(), errors::HealthCheckRedisError> { + self.diesel_store.health_check_redis(db).await + } + + async fn health_check_locker( + &self, + state: &routes::AppState, + ) -> CustomResult<(), errors::HealthCheckLockerError> { + self.diesel_store.health_check_locker(state).await + } +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0357cedd443..6625a206be2 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -253,9 +253,10 @@ pub struct Health; impl Health { pub fn server(state: AppState) -> Scope { - web::scope("") + web::scope("health") .app_data(web::Data::new(state)) - .service(web::resource("/health").route(web::get().to(health))) + .service(web::resource("").route(web::get().to(health))) + .service(web::resource("/deep_check").route(web::post().to(deep_health_check))) } } diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index 7c7f29bd181..f07b744f7f5 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -1,7 +1,9 @@ +use actix_web::web; +use api_models::health_check::RouterHealthCheckResponse; use router_env::{instrument, logger, tracing}; -use crate::routes::metrics; - +use super::app; +use crate::{routes::metrics, services}; /// . // #[logger::instrument(skip_all, name = "name1", level = "warn", fields( key1 = "val1" ))] #[instrument(skip_all)] @@ -11,3 +13,59 @@ pub async fn health() -> impl actix_web::Responder { logger::info!("Health was called"); actix_web::HttpResponse::Ok().body("health is good") } + +#[instrument(skip_all)] +pub async fn deep_health_check(state: web::Data<app::AppState>) -> impl actix_web::Responder { + metrics::HEALTH_METRIC.add(&metrics::CONTEXT, 1, &[]); + let db = &*state.store; + let mut status_code = 200; + logger::info!("Deep health check was called"); + + logger::debug!("Database health check begin"); + + let db_status = match db.health_check_db().await { + Ok(_) => "Health is good".to_string(), + Err(err) => { + status_code = 500; + err.to_string() + } + }; + logger::debug!("Database health check end"); + + logger::debug!("Redis health check begin"); + + let redis_status = match db.health_check_redis(db).await { + Ok(_) => "Health is good".to_string(), + Err(err) => { + status_code = 500; + err.to_string() + } + }; + + logger::debug!("Redis health check end"); + + logger::debug!("Locker health check begin"); + + let locker_status = match db.health_check_locker(&state).await { + Ok(_) => "Health is good".to_string(), + Err(err) => { + status_code = 500; + err.to_string() + } + }; + + logger::debug!("Locker health check end"); + + let response = serde_json::to_string(&RouterHealthCheckResponse { + database: db_status, + redis: redis_status, + locker: locker_status, + }) + .unwrap_or_default(); + + if status_code == 200 { + services::http_response_json(response) + } else { + services::http_server_error_json_response(response) + } +} diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 92fda578727..71687e02c12 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1138,6 +1138,14 @@ pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpRe .body(response) } +pub fn http_server_error_json_response<T: body::MessageBody + 'static>( + response: T, +) -> HttpResponse { + HttpResponse::InternalServerError() + .content_type(mime::APPLICATION_JSON) + .body(response) +} + pub fn http_response_json_with_headers<T: body::MessageBody + 'static>( response: T, mut headers: Vec<(String, String)>, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index cc7353dcda6..fca85c41699 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -10,6 +10,7 @@ use router_env::tracing_actix_web::RequestId; use super::{request::Maskable, Request}; use crate::{ configs::settings::{Locker, Proxy}, + consts::LOCKER_HEALTH_CALL_PATH, core::{ errors::{ApiClientError, CustomResult}, payments, @@ -119,6 +120,7 @@ pub fn proxy_bypass_urls(locker: &Locker) -> Vec<String> { format!("{locker_host_rs}/cards/add"), format!("{locker_host_rs}/cards/retrieve"), format!("{locker_host_rs}/cards/delete"), + format!("{locker_host_rs}{}", LOCKER_HEALTH_CALL_PATH), format!("{locker_host}/card/addCard"), format!("{locker_host}/card/getCard"), format!("{locker_host}/card/deleteCard"), diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index f0cbebf78c5..50173bb1c73 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -376,3 +376,53 @@ pub enum ConnectorError { #[error("Missing 3DS redirection payload: {field_name}")] MissingConnectorRedirectionPayload { field_name: &'static str }, } + +#[derive(Debug, thiserror::Error)] +pub enum HealthCheckDBError { + #[error("Error while connecting to database")] + DBError, + #[error("Error while writing to database")] + DBWriteError, + #[error("Error while reading element in the database")] + DBReadError, + #[error("Error while deleting element in the database")] + DBDeleteError, + #[error("Unpredictable error occurred")] + UnknownError, + #[error("Error in database transaction")] + TransactionError, +} + +impl From<diesel::result::Error> for HealthCheckDBError { + fn from(error: diesel::result::Error) -> Self { + match error { + diesel::result::Error::DatabaseError(_, _) => Self::DBError, + + diesel::result::Error::RollbackErrorOnCommit { .. } + | diesel::result::Error::RollbackTransaction + | diesel::result::Error::AlreadyInTransaction + | diesel::result::Error::NotInTransaction + | diesel::result::Error::BrokenTransactionManager => Self::TransactionError, + + _ => Self::UnknownError, + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum HealthCheckRedisError { + #[error("Failed to establish Redis connection")] + RedisConnectionError, + #[error("Failed to set key value in Redis")] + SetFailed, + #[error("Failed to get key value in Redis")] + GetFailed, + #[error("Failed to delete key value in Redis")] + DeleteFailed, +} + +#[derive(Debug, Clone, thiserror::Error)] +pub enum HealthCheckLockerError { + #[error("Failed to establish Locker connection")] + FailedToCallLocker, +}
2023-12-27T15:29:09Z
## Description <!-- Describe your changes in detail --> This PR adds support for performing a deeper health check of the application which includes: * Database connection check with read, write and delete queries (Added support for database transaction too) * Redis connection check with set, get and delete key (Set key with expiry of 30sec) * Locker health call from Hyperswitch application The deep health check API returns a 200 status code if all the components are in good health, but returns 500 if at least one component's health is down ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
72968dcecf16c8821a383a826e4e35408b035633
1. Hit `/health` for getting just the application health. 2. Hit `/health/deep_check` for getting deep report of components health * Test case 1 (Application not able to connect to database because postgresql is down) ![image](https://github.com/juspay/hyperswitch/assets/70657455/5e8af307-0b01-4008-a8e7-30d1aa8d3ed4) * Test case 2 (Database Insert query failing because of duplication) ![image](https://github.com/juspay/hyperswitch/assets/70657455/0775c8db-bf43-4cf1-b197-33dea3b51058) * Test case 3 (Locker is down) ![image](https://github.com/juspay/hyperswitch/assets/70657455/2bc6d734-8da5-4b87-8138-d22ba76a0bc7) * Test case 4 (Locker is up but key custodian locked) ![image](https://github.com/juspay/hyperswitch/assets/70657455/35b83c7a-388f-4128-8913-66f1a8e23bde) * Test case 5 (Locker is up with key custodian unlocked) ![image](https://github.com/juspay/hyperswitch/assets/70657455/ed64322e-08d0-458e-af69-fe8010d21a61)
[ "crates/api_models/src/health_check.rs", "crates/api_models/src/lib.rs", "crates/router/src/consts.rs", "crates/router/src/db.rs", "crates/router/src/db/health_check.rs", "crates/router/src/db/kafka_store.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/health.rs", "crates/router/sr...
juspay/hyperswitch
juspay__hyperswitch-3622
Bug: [FEATURE] Add required fields for giropay ### Feature Description Add giropay wallet required fields for all connectors that implement Giropay ### Possible Implementation Add required fields for Giropay ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 87999f0e9e9..f592cfeb9eb 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -390,6 +390,8 @@ bank_debit.sepa = { connector_list = "gocardless" } # Mandate supported payment bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} # Mandate supported payment method type and connector for bank_redirect bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" } +bank_redirect.giropay = {connector_list = "adyen,globalpay"} + # Required fields info used while listing the payment_method_data diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 2c5d16e3e3c..6c721ab3a9f 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -117,8 +117,10 @@ pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" -bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" +bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" +bank_redirect.giropay.connector_list = "adyen,globalpay" + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 964281c52bb..b8a4f7ef20f 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -117,8 +117,9 @@ pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" -bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" +bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" +bank_redirect.giropay.connector_list = "adyen,globalpay" [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index aa2377cf8a0..f6e1ca01f19 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -117,8 +117,10 @@ pay_later.klarna.connector_list = "adyen" wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon" wallet.google_pay.connector_list = "stripe,adyen,cybersource" wallet.paypal.connector_list = "adyen" -bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} -bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.ideal.connector_list = "stripe,adyen,globalpay" +bank_redirect.sofort.connector_list = "stripe,adyen,globalpay" +bank_redirect.giropay.connector_list = "adyen,globalpay" + [multiple_api_version_supported_connectors] supported_connectors = "braintree" diff --git a/config/development.toml b/config/development.toml index 20abb7bd6f3..5343e485a08 100644 --- a/config/development.toml +++ b/config/development.toml @@ -483,6 +483,7 @@ bank_debit.becs = { connector_list = "gocardless"} bank_debit.sepa = { connector_list = "gocardless"} bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.giropay = {connector_list = "adyen,globalpay"} [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = [] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index e6dc01afa74..3aeb6754fbb 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -348,6 +348,8 @@ bank_debit.becs = { connector_list = "gocardless"} bank_debit.sepa = { connector_list = "gocardless"} bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.giropay = {connector_list = "adyen,globalpay"} + [connector_customer] connector_list = "gocardless,stax,stripe" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index a4f052549bd..6a9b7a12a72 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1272,7 +1272,7 @@ pub enum BankRedirectData { }, Giropay { /// The billing details for bank redirection - billing_details: BankRedirectBilling, + billing_details: Option<BankRedirectBilling>, /// Bank account details for Giropay #[schema(value_type = Option<String>)] diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 7b88c9c2dc7..1f041c27a74 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -4480,14 +4480,226 @@ impl Default for super::settings::RequiredFields { enums::PaymentMethodType::Giropay, ConnectorFields { fields: HashMap::from([ + ( + enums::Connector::Aci, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + ( + "payment_method_data.bank_redirect.giropay.country".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_redirect.giropay.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserCountry { + options: vec![ + "DE".to_string(), + ]}, + value: None, + } + ) + ]), + common: HashMap::new(), + } + ), + ( + enums::Connector::Adyen, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ( + enums::Connector::Globalpay, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::from([ + ("billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry { + options: vec![ + "DE".to_string(), + ] + }, + value: None, + } + ) + ]), + } + ), + ( + enums::Connector::Mollie, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: HashMap::new(), + } + ), + ( + enums::Connector::Nuvei, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate:HashMap::from([ + ( + "email".to_string(), + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "billing_last_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry{ + options: vec![ + "DE".to_string(), + ] + }, + value: None, + } + )] + ), + common: HashMap::new(), + } + ), + ( + enums::Connector::Paypal, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + ("payment_method_data.bank_redirect.giropay.country".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_redirect.giropay.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserCountry { + options: vec![ + "DE".to_string(), + ] + }, + value: None, + } + ), + ( + "payment_method_data.bank_redirect.giropay.billing_details.billing_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_redirect.giropay.billing_details.billing_name".to_string(), + display_name: "billing_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ) + ]), + common: HashMap::new(), + } + ), ( enums::Connector::Stripe, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + ("payment_method_data.bank_redirect.giropay.billing_details.billing_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.bank_redirect.giropay.billing_details.billing_name".to_string(), + display_name: "billing_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ) + ]), + common: HashMap::new(), + } + ), + ( + enums::Connector::Shift4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), + ( + enums::Connector::Trustpay, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::from([ + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + ), + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserAddressLine1, + value: None, + } + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserAddressCity, + value: None, + } + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserAddressPincode, + value: None, + } + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry { + options: vec![ + "DE".to_string(), + ] + }, + value: None, + } + ), + ]), + common: HashMap::new(), + } + ), ]), }, ), diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 97cef72b02a..92c7e164c4c 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -166,10 +166,15 @@ impl api_models::payments::BankRedirectData::Giropay { bank_account_bic, bank_account_iban, + country, .. } => Self::BankRedirect(Box::new(BankRedirectionPMData { payment_brand: PaymentBrand::Giropay, - bank_account_country: Some(api_models::enums::CountryAlpha2::DE), + bank_account_country: Some(country.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "giropay.country", + }, + )?), bank_account_bank_name: None, bank_account_bic: bank_account_bic.clone(), bank_account_iban: bank_account_iban.clone(), diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 88595585fe1..1447cf75be7 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -315,7 +315,12 @@ fn get_payment_source( country, .. } => Ok(PaymentSourceItem::Giropay(RedirectRequest { - name: billing_details.get_billing_name()?, + name: billing_details + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "giropay.billing_details", + })? + .get_billing_name()?, country_code: country.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "giropay.country", })?, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 8d397d0ebb9..69bbceab133 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -18,7 +18,8 @@ use url::Url; use crate::{ collect_missing_value_keys, connector::utils::{ - self as connector_util, ApplePay, ApplePayDecrypt, PaymentsPreProcessingData, RouterData, + self as connector_util, ApplePay, ApplePayDecrypt, BankRedirectBillingData, + PaymentsPreProcessingData, RouterData, }, core::errors, services, @@ -1108,7 +1109,14 @@ impl TryFrom<(&payments::BankRedirectData, Option<bool>)> for StripeBillingAddre payments::BankRedirectData::Giropay { billing_details, .. } => Ok(Self { - name: billing_details.billing_name.clone(), + name: Some( + billing_details + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "giropay.billing_details", + })? + .get_billing_name()?, + ), ..Self::default() }), payments::BankRedirectData::Ideal { diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index c55663d59f4..a21c88a2ce9 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use url::Url; use crate::{ - connector::utils::{self, CardData}, + connector::utils::{self, BankRedirectBillingData, CardData}, core::errors, services, types::{ @@ -385,11 +385,12 @@ fn make_bank_redirect_request( { PaymentMethodSpecificData::PaymentProduct816SpecificInput(Box::new(Giropay { bank_account_iban: BankAccountIban { - account_holder_name: billing_details.billing_name.clone().ok_or( - errors::ConnectorError::MissingRequiredField { - field_name: "billing_details.billing_name", - }, - )?, + account_holder_name: billing_details + .clone() + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "giropay.billing_details", + })? + .get_billing_name()?, iban: bank_account_iban.clone(), }, })) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 954336070d5..ee5a0c3b44c 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -248,6 +248,8 @@ bank_debit.becs = { connector_list = "gocardless"} bank_debit.sepa = { connector_list = "gocardless"} bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"} bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"} +bank_redirect.giropay = {connector_list = "adyen,globalpay"} + [analytics] source = "sqlx" diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 9afd5182529..4fef244c461 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5155,12 +5155,16 @@ "giropay": { "type": "object", "required": [ - "billing_details", "country" ], "properties": { "billing_details": { - "$ref": "#/components/schemas/BankRedirectBilling" + "allOf": [ + { + "$ref": "#/components/schemas/BankRedirectBilling" + } + ], + "nullable": true }, "bank_account_bic": { "type": "string",
2023-12-21T15:05:05Z
## Description <!-- Describe your changes in detail --> Resolves [#3622](https://github.com/juspay/hyperswitch/issues/3622) ### Test Cases 1. Create a giropay payment with mollie with empty payment method object. The payment should succeed. ``` { "amount": 1000, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "payment_method": "bank_redirect", "payment_method_type": "giropay", "payment_method_data": { "bank_redirect": { "giropay": { } } } } ``` Must be tested for each of this connectors 1.ACI ``` Required fields: payment_method_data.bank_redirect.giropay.country ``` 2. Adyen ``` None ``` 3. GlobalPayments ``` Required fields: billing.address.country ``` 4. Mollie ``` None ``` 5. Nuvie ``` Required fields: email billing.address.first_name billing.address.last_name billing.address.country ``` 6. Paypal ``` Required fields: payment_method_data.bank_redirect.giropay.billing_details.billing_name payment_method_data.bank_redirect.giropay.country ``` 7. Shift4 ``` None ``` 8. Stripe ``` Required fields payment_method_data.bank_redirect.giropay.billing_details.billing_name ``` 9. Trustpay ``` Required fields: billing.address.first_name billing.address.line1 billing.address.city billing.address.zip billing.address.country ``` -> Create a payment with confirm `false` -> list payment methods, with client secret and publishable key ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret={{client_secret}}' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:{{api_key}}' \ --data '' ``` Required fields must be populated, according to the connector
54fb61eeebec503f599774fe9e97f6b6ce3f1458
[ "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/src/payments.rs", "crates/router/src/configs/defaults.rs", "crates/router/src...
juspay/hyperswitch
juspay__hyperswitch-2090
Bug: [BUG] Add metrics in router scheduler flow as it is being ignored now ### Bug Description Router is not maintaining any metrics about the task added in scheduler. this has to be fixed File: crates/router/src/core/payments/helpers.rs Method: add_domain_task_to_pt ### Expected Behavior Metrics has to be added to know the TASKS_ADDED_COUNT and TASKS_RESET_COUNT ### Actual Behavior Currently those are not available ### Steps To Reproduce NA ### Context For The Bug _No response_ ### Environment NA ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index c1ddc43cd65..78d4e801e8f 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -270,6 +270,11 @@ pub async fn add_api_key_expiry_task( api_key_expiry_tracker.key_id ) })?; + metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes("flow", "ApiKeyExpiry")], + ); Ok(()) } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 39bc54fa157..f005920c24f 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2855,6 +2855,14 @@ impl TempLockerCardSupport { ) .await?; metrics::TOKENIZED_DATA_COUNT.add(&metrics::CONTEXT, 1, &[]); + metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "flow", + "DeleteTokenizeData", + )], + ); Ok(card) } } diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 070bca234c8..59be4087eaa 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1026,7 +1026,18 @@ pub async fn retry_delete_tokenize( let schedule_time = get_delete_tokenize_schedule_time(db, pm, pt.retry_count).await; match schedule_time { - Some(s_time) => pt.retry(db.as_scheduler(), s_time).await, + Some(s_time) => { + let retry_schedule = pt.retry(db.as_scheduler(), s_time).await; + metrics::TASKS_RESET_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "flow", + "DeleteTokenizeData", + )], + ); + retry_schedule + } None => { pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) .await diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 7230d74e9a9..e15fed0327f 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -986,14 +986,30 @@ where match schedule_time { Some(stime) => { if !requeue { - // scheduler_metrics::TASKS_ADDED_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics + // Here, increment the count of added tasks every time a payment has been confirmed or PSync has been called + metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "flow", + format!("{:#?}", operation), + )], + ); super::add_process_sync_task(&*state.store, payment_attempt, stime) .await .into_report() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while adding task to process tracker") } else { - // scheduler_metrics::TASKS_RESET_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics + // When the requeue is true, we reset the tasks count as we reset the task every time it is requeued + metrics::TASKS_RESET_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "flow", + format!("{:#?}", operation), + )], + ); super::reset_process_sync_task(&*state.store, payment_attempt, stime) .await .into_report() diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index e60c341dedc..4b1c33296e6 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1088,6 +1088,12 @@ pub async fn add_refund_sync_task( refund.refund_id ) })?; + metrics::TASKS_ADDED_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes("flow", "Refund")], + ); + Ok(response) } @@ -1170,7 +1176,15 @@ pub async fn retry_refund_sync_task( get_refund_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count).await?; match schedule_time { - Some(s_time) => pt.retry(db.as_scheduler(), s_time).await, + Some(s_time) => { + let retry_schedule = pt.retry(db.as_scheduler(), s_time).await; + metrics::TASKS_RESET_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes("flow", "Refund")], + ); + retry_schedule + } None => { pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) .await diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index b3629ab7d52..6c3293dba9d 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -113,5 +113,8 @@ counter_metric!(AUTO_RETRY_GSM_MATCH_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_EXHAUSTED_COUNT, GLOBAL_METER); counter_metric!(AUTO_RETRY_PAYMENT_COUNT, GLOBAL_METER); +counter_metric!(TASKS_ADDED_COUNT, GLOBAL_METER); // Tasks added to process tracker +counter_metric!(TASKS_RESET_COUNT, GLOBAL_METER); // Tasks reset in process tracker for requeue flow + pub mod request; pub mod utils; diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index 62d8a54c402..eb3c1d9c1ce 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -115,6 +115,12 @@ Team Hyperswitch"), let task_ids = vec![task_id]; db.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data) .await?; + // Remaining tasks are re-scheduled, so will be resetting the added count + metrics::TASKS_RESET_COUNT.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes("flow", "ApiKeyExpiry")], + ); } Ok(()) diff --git a/crates/scheduler/src/metrics.rs b/crates/scheduler/src/metrics.rs index 134f5599b31..ca4fb9ec242 100644 --- a/crates/scheduler/src/metrics.rs +++ b/crates/scheduler/src/metrics.rs @@ -6,8 +6,6 @@ global_meter!(PT_METER, "PROCESS_TRACKER"); histogram_metric!(CONSUMER_STATS, PT_METER, "CONSUMER_OPS"); counter_metric!(PAYMENT_COUNT, PT_METER); // No. of payments created -counter_metric!(TASKS_ADDED_COUNT, PT_METER); // Tasks added to process tracker -counter_metric!(TASKS_RESET_COUNT, PT_METER); // Tasks reset in process tracker for requeue flow counter_metric!(TASKS_PICKED_COUNT, PT_METER); // Tasks picked by counter_metric!(BATCHES_CREATED, PT_METER); // Batches added to stream counter_metric!(BATCHES_CONSUMED, PT_METER); // Batches consumed by consumer
2023-12-21T11:29:29Z
## Description <!-- Describe your changes in detail --> Currently `TASKS_ADDED_COUNT` and `TASKS_RESET_COUNT` metrics does not exist in router to track the tasks added in scheduler. This PR aims at adding that. Closes #2090 ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> We need to track the tasks added in scheduler. # ### Local setup: Modify 3 files: - `docker-compose.yml`: Expose the `otel-collector` port by replacing `"4317"` with `"4317:4317"` - `development.toml`: Enable logging by setting `metrics_enabled` to `true` and `otel_exporter_otlp_endpoint` to `http://localhost:4317` - `otel-collector.yml`: Add logging in exporters of pipeline service: `[prometheus, logging]` instead of `[prometheus]` - Open a terminal window, start server by executing: `cargo r` - Create another terminal window for psql, execute: ``` psql hyperswitch_db \x \dt table process_tracker; ``` - Create another 3 terminal windows. One for consumer, another for producer and another for Grafana. Execute: ``` # In consumer terminal window SCHEDULER_FLOW=consumer cargo r --bin scheduler # In producer terminal window SCHEDULER_FLOW=producer cargo r --bin scheduler # In Grafana terminal window docker compose up -d grafana prometheus otel-collector ``` - Execute `curl telnet://localhost:4317` in yet another terminal window to see if this URL can be accessed or not - Grafana username/password - admin/admin > incase reset is required, execute in terminal: > ` grafana-cli admin reset-admin-password <new-password>` In env: - Open Grafana > VM Single > `Metric:router_TASKS_ADDED_COUNT_total`, `label:job=router` > `Run Query`
5ad3f8939afafce3eec39704dcaa92270b384dcd
Did a few payments (Ran Stripe and Volt collection a few times): <img width="1728" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/1e2dca12-c7e8-453c-97c9-bc95e8dbf742"> ### Local setup: Modify 3 files: - `docker-compose.yml`: Expose the `otel-collector` port by replacing `"4317"` with `"4317:4317"` - `development.toml`: Enable logging by setting `metrics_enabled` to `true` and `otel_exporter_otlp_endpoint` to `http://localhost:4317` - `otel-collector.yml`: Add logging in exporters of pipeline service: `[prometheus, logging]` instead of `[prometheus]` - Open a terminal window, start server by executing: `cargo r` - Create another terminal window for psql, execute: ``` psql hyperswitch_db \x \dt table process_tracker; ``` - Create another 3 terminal windows. One for consumer, another for producer and another for Grafana. Execute: ```
[ "crates/router/src/core/api_keys.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payment_methods/vault.rs", "crates/router/src/core/payments/helpers.rs", "crates/router/src/core/refunds.rs", "crates/router/src/routes/metrics.rs", "crates/router/src/workflows/api_key_expir...
juspay/hyperswitch
juspay__hyperswitch-3175
Bug: [BUG] No provision for approving payments kept in ManualReview state for FRM flows ### Bug Description Once a fraudulent payment transaction is identified before authorization, it can be canceled or kept in manual reviewing state. If it is canceled, the payment is marked as a `failed` transaction. If the decision for the transaction is `manual_review`, it needs to be reviewed by the consumer and can be approved or rejected. If the transaction seem legit, the consumer can hit the `/approve` endpoint for approving the payments. This flow is broken. ### Expected Behavior If a txn is marked as `fraudulent`, it should still proceed for authorization, without capturing the amount. Upon approval, the amount can be captured. Upon rejection, the txn can be voided. ### Actual Behavior If a txn is marked as `fraudulent`, the flow would store the `payment_method_data` in locker, which could be later fetched if approval was given. Upon approval, it tries to fetch `payment_method_data` from locker, but fails (due to recent locker changes). Upon rejection, it marks the txn as `failed`. ### Steps To Reproduce 1. Create a merchant account 2. Create an API key 3. Add payment connector 4. Add FRM connector (enable pre flows for card, and set merchant_decision to `manual_review`) 5. Create a payment using debit / credit card w huge amounts, so it can be marked as fraudulent 6. Returned status - `requires_merchant_action` 7. Try to approve this payment 8. Returned error - payment_method_data not found ### Context For The Bug This is specifically for Pre-Transaction FRM flows, where the decision is set to `manual_review`. If a txn is stuck with state `requires_merchant_action`, those transactions can never be approved. They can only be rejected. ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `rustc 1.74.1 (a28077b28 2023-12-04)` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index ad3a7638774..0e3f67c051b 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -431,6 +431,7 @@ pub async fn pre_payment_frm_core<'a, F>( frm_configs: FrmConfigsObject, customer: &Option<domain::Customer>, should_continue_transaction: &mut bool, + should_continue_capture: &mut bool, key_store: domain::MerchantKeyStore, ) -> RouterResult<Option<FrmData>> where @@ -466,13 +467,12 @@ where .await?; let frm_fraud_check = frm_data_updated.fraud_check.clone(); payment_data.frm_message = Some(frm_fraud_check.clone()); - if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) - //DontTakeAction - { - *should_continue_transaction = false; + if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) { if matches!(frm_configs.frm_action, api_enums::FrmAction::CancelTxn) { + *should_continue_transaction = false; frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction); } else if matches!(frm_configs.frm_action, api_enums::FrmAction::ManualReview) { + *should_continue_capture = false; frm_info.suggested_action = Some(FrmSuggestion::FrmManualReview); } } @@ -582,6 +582,7 @@ pub async fn call_frm_before_connector_call<'a, F, Req, Ctx>( frm_info: &mut Option<FrmInfo<F>>, customer: &Option<domain::Customer>, should_continue_transaction: &mut bool, + should_continue_capture: &mut bool, key_store: domain::MerchantKeyStore, ) -> RouterResult<Option<FrmConfigsObject>> where @@ -615,6 +616,7 @@ where frm_configs, customer, should_continue_transaction, + should_continue_capture, key_store, ) .await?; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 21cdec92ccb..5b6789dad0b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -181,6 +181,8 @@ where #[allow(unused_variables, unused_mut)] let mut should_continue_transaction: bool = true; #[cfg(feature = "frm")] + let mut should_continue_capture: bool = true; + #[cfg(feature = "frm")] let frm_configs = if state.conf.frm.enabled { frm_core::call_frm_before_connector_call( db, @@ -191,6 +193,7 @@ where &mut frm_info, &customer, &mut should_continue_transaction, + &mut should_continue_capture, key_store.clone(), ) .await? @@ -199,12 +202,25 @@ where }; #[cfg(feature = "frm")] logger::debug!( - "should_cancel_transaction: {:?} {:?} ", + "frm_configs: {:?}\nshould_cancel_transaction: {:?}\nshould_continue_capture: {:?}", frm_configs, - should_continue_transaction + should_continue_transaction, + should_continue_capture, ); if should_continue_transaction { + #[cfg(feature = "frm")] + match ( + should_continue_capture, + payment_data.payment_attempt.capture_method, + ) { + (false, Some(storage_enums::CaptureMethod::Automatic)) + | (false, Some(storage_enums::CaptureMethod::Scheduled)) => { + payment_data.payment_attempt.capture_method = + Some(storage_enums::CaptureMethod::Manual); + } + _ => (), + }; payment_data = match connector_details { api::ConnectorCallType::PreDetermined(connector) => { let schedule_time = if should_add_task_to_process_tracker { @@ -233,6 +249,10 @@ where &validate_result, schedule_time, header_payload, + #[cfg(feature = "frm")] + frm_info.as_ref().and_then(|fi| fi.suggested_action), + #[cfg(not(feature = "frm"))] + None, ) .await?; let operation = Box::new(PaymentResponse); @@ -284,6 +304,10 @@ where &validate_result, schedule_time, header_payload, + #[cfg(feature = "frm")] + frm_info.as_ref().and_then(|fi| fi.suggested_action), + #[cfg(not(feature = "frm"))] + None, ) .await?; @@ -311,6 +335,10 @@ where &customer, &validate_result, schedule_time, + #[cfg(feature = "frm")] + frm_info.as_ref().and_then(|fi| fi.suggested_action), + #[cfg(not(feature = "frm"))] + None, ) .await?; }; @@ -996,6 +1024,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, Ctx>( validate_result: &operations::ValidateResult<'_>, schedule_time: Option<time::PrimitiveDateTime>, header_payload: HeaderPayload, + frm_suggestion: Option<storage_enums::FrmSuggestion>, ) -> RouterResult<router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -1172,7 +1201,7 @@ where merchant_account.storage_scheme, updated_customer, key_store, - None, + frm_suggestion, header_payload, ) .await?; @@ -2109,6 +2138,7 @@ pub fn should_call_connector<Op: Debug, F: Clone>( } "CompleteAuthorize" => true, "PaymentApprove" => true, + "PaymentReject" => true, "PaymentSession" => true, "PaymentIncrementalAuthorization" => matches!( payment_data.payment_intent.status, diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index cddbc89acff..6d3697caabd 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -2,54 +2,51 @@ use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; -use data_models::mandates::MandateData; -use error_stack::{report, IntoReport, ResultExt}; +use error_stack::{IntoReport, ResultExt}; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ - errors::{self, CustomResult, RouterResult, StorageErrorExt}, + errors::{self, RouterResult, StorageErrorExt}, payment_methods::PaymentMethodRetrieve, - payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, + payments::{helpers, operations, PaymentAddress, PaymentData}, utils as core_utils, }, - db::StorageInterface, routes::AppState, services, types::{ - self, api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, - utils::{self, OptionExt}, + utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] -#[operation(operations = "all", flow = "authorize")] +#[operation(operations = "all", flow = "capture")] pub struct PaymentApprove; #[async_trait] impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> - GetTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentApprove + GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentApprove { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - request: &api::PaymentsRequest, - mandate_type: Option<api::MandateTransactionType>, + _request: &api::PaymentsCaptureRequest, + _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, - ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, Ctx>> { + ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, Ctx>> { let db = &*state.store; let merchant_id = &merchant_account.merchant_id; let storage_scheme = merchant_account.storage_scheme; - let (mut payment_intent, mut payment_attempt, currency, amount); + let (mut payment_intent, payment_attempt, currency, amount); let payment_id = payment_id .get_payment_intent_id() @@ -59,9 +56,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - payment_intent.setup_future_usage = request - .setup_future_usage - .or(payment_intent.setup_future_usage); helpers::validate_payment_status_against_not_allowed_statuses( &payment_intent.status, @@ -69,7 +63,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, ], - "confirm", + "approve", )?; let profile_id = payment_intent @@ -87,31 +81,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> id: profile_id.to_string(), })?; - let ( - token, - payment_method, - payment_method_type, - setup_mandate, - recurring_mandate_payment_data, - mandate_connector, - ) = helpers::get_token_pm_type_mandate_details( - state, - request, - mandate_type.clone(), - merchant_account, - key_store, - ) - .await?; - - let browser_info = request - .browser_info - .clone() - .map(|x| utils::Encode::<types::BrowserInformation>::encode_to_value(&x)) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "browser_info", - })?; - let attempt_id = payment_intent.active_attempt.get_id().clone(); payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( @@ -123,35 +92,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; - let token = token.or_else(|| payment_attempt.payment_token.clone()); - - helpers::validate_pm_or_token_given( - &request.payment_method, - &request.payment_method_data, - &request.payment_method_type, - &mandate_type, - &token, - )?; - - payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); - payment_attempt.browser_info = browser_info; - payment_attempt.payment_method_type = - payment_method_type.or(payment_attempt.payment_method_type); - payment_attempt.payment_experience = request.payment_experience; currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); - helpers::validate_customer_id_mandatory_cases( - request.setup_future_usage.is_some(), - &payment_intent - .customer_id - .clone() - .or_else(|| request.customer_id.clone()), - )?; - let shipping_address = helpers::create_or_find_address_for_payment_by_request( db, - request.shipping.as_ref(), + None, payment_intent.shipping_address_id.as_deref(), merchant_id, payment_intent.customer_id.as_ref(), @@ -162,7 +108,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> .await?; let billing_address = helpers::create_or_find_address_for_payment_by_request( db, - request.billing.as_ref(), + None, payment_intent.billing_address_id.as_deref(), merchant_id, payment_intent.customer_id.as_ref(), @@ -172,47 +118,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ) .await?; - let redirect_response = request - .feature_metadata - .as_ref() - .and_then(|fm| fm.redirect_response.clone()); - payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id); payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id); - payment_intent.return_url = request - .return_url - .as_ref() - .map(|a| a.to_string()) - .or(payment_intent.return_url); - - payment_intent.allowed_payment_method_types = request - .get_allowed_payment_method_types_as_value() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error converting allowed_payment_types to Value")? - .or(payment_intent.allowed_payment_method_types); - - payment_intent.connector_metadata = request - .get_connector_metadata_as_value() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error converting connector_metadata to Value")? - .or(payment_intent.connector_metadata); - - payment_intent.feature_metadata = request - .get_feature_metadata_as_value() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error converting feature_metadata to Value")? - .or(payment_intent.feature_metadata); - - payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); - - // The operation merges mandate data from both request and payment_attempt - let setup_mandate = setup_mandate.map(|mandate_data| MandateData { - customer_acceptance: mandate_data.customer_acceptance, - mandate_type: payment_attempt - .mandate_details - .clone() - .or(mandate_data.mandate_type), - }); let frm_response = db .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.merchant_id.clone()) @@ -228,49 +135,41 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_attempt, currency, amount, - email: request.email.clone(), + email: None, mandate_id: None, - mandate_connector, - setup_mandate, - token, + mandate_connector: None, + setup_mandate: None, + token: None, address: PaymentAddress { shipping: shipping_address.as_ref().map(|a| a.into()), billing: billing_address.as_ref().map(|a| a.into()), }, - confirm: request.confirm, - payment_method_data: request.payment_method_data.clone(), + confirm: None, + payment_method_data: None, force_sync: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], - card_cvc: request.card_cvc.clone(), + card_cvc: None, creds_identifier: None, pm_token: None, connector_customer_id: None, - recurring_mandate_payment_data, + recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, - redirect_response, + redirect_response: None, surcharge_details: None, frm_message: frm_response.ok(), payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], - frm_metadata: request.frm_metadata.clone(), + frm_metadata: None, }; - let customer_details = Some(CustomerDetails { - customer_id: request.customer_id.clone(), - name: request.name.clone(), - email: request.email.clone(), - phone: request.phone.clone(), - phone_country_code: request.phone_country_code.clone(), - }); - let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), - customer_details, + customer_details: None, payment_data, business_profile, }; @@ -279,91 +178,9 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> } } -#[async_trait] -impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest, Ctx> - for PaymentApprove -{ - #[instrument(skip_all)] - async fn get_or_create_customer_details<'a>( - &'a self, - db: &dyn StorageInterface, - payment_data: &mut PaymentData<F>, - request: Option<CustomerDetails>, - key_store: &domain::MerchantKeyStore, - ) -> CustomResult< - ( - BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, - Option<domain::Customer>, - ), - errors::StorageError, - > { - helpers::create_customer_if_not_exist( - Box::new(self), - db, - payment_data, - request, - &key_store.merchant_id, - key_store, - ) - .await - } - - #[instrument(skip_all)] - async fn make_pm_data<'a>( - &'a self, - state: &'a AppState, - payment_data: &mut PaymentData<F>, - _storage_scheme: storage_enums::MerchantStorageScheme, - merchant_key_store: &domain::MerchantKeyStore, - customer: &Option<domain::Customer>, - ) -> RouterResult<( - BoxedOperation<'a, F, api::PaymentsRequest, Ctx>, - Option<api::PaymentMethodData>, - )> { - let (op, payment_method_data) = helpers::make_pm_data( - Box::new(self), - state, - payment_data, - merchant_key_store, - customer, - ) - .await?; - - utils::when(payment_method_data.is_none(), || { - Err(errors::ApiErrorResponse::PaymentMethodNotFound) - })?; - - Ok((op, payment_method_data)) - } - - #[instrument(skip_all)] - async fn add_task_to_process_tracker<'a>( - &'a self, - _state: &'a AppState, - _payment_attempt: &storage::PaymentAttempt, - _requeue: bool, - _schedule_time: Option<time::PrimitiveDateTime>, - ) -> CustomResult<(), errors::ApiErrorResponse> { - Ok(()) - } - - async fn get_connector<'a>( - &'a self, - _merchant_account: &domain::MerchantAccount, - state: &AppState, - request: &api::PaymentsRequest, - _payment_intent: &storage::PaymentIntent, - _key_store: &domain::MerchantKeyStore, - ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { - // Use a new connector in the confirm call or use the same one which was passed when - // creating the payment or if none is passed then use the routing algorithm - helpers::get_connector_default(state, request.routing.clone()).await - } -} - #[async_trait] impl<F: Clone, Ctx: PaymentMethodRetrieve> - UpdateTracker<F, PaymentData<F>, api::PaymentsRequest, Ctx> for PaymentApprove + UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest, Ctx> for PaymentApprove { #[instrument(skip_all)] async fn update_trackers<'b>( @@ -377,7 +194,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> _frm_suggestion: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>, PaymentData<F>, )> where @@ -401,16 +218,16 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> } } -impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::PaymentsRequest, Ctx> - for PaymentApprove +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> + ValidateRequest<F, api::PaymentsCaptureRequest, Ctx> for PaymentApprove { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, - request: &api::PaymentsRequest, + request: &api::PaymentsCaptureRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, api::PaymentsRequest, Ctx>, + BoxedOperation<'b, F, api::PaymentsCaptureRequest, Ctx>, operations::ValidateResult<'a>, )> { let request_merchant_id = request.merchant_id.as_deref(); @@ -420,28 +237,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen expected_format: "merchant_id from merchant account".to_string(), })?; - helpers::validate_payment_method_fields_present(request)?; - - let mandate_type = - helpers::validate_mandate(request, payments::is_operation_confirm(self))?; - let payment_id = request - .payment_id - .clone() - .ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?; - Ok(( Box::new(self), operations::ValidateResult { merchant_id: &merchant_account.merchant_id, - payment_id: payment_id - .and_then(|id| core_utils::validate_id(id, "payment_id")) - .into_report()?, - mandate_type, - storage_scheme: merchant_account.storage_scheme, - requeue: matches!( - request.retry_action, - Some(api_models::enums::RetryAction::Requeue) + payment_id: api::PaymentIdType::PaymentIntentId( + core_utils::validate_id(request.payment_id.clone(), "payment_id") + .into_report()?, ), + mandate_type: None, + storage_scheme: merchant_account.storage_scheme, + requeue: false, }, )) } diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 37c7dfd1bae..e958422d312 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -1,6 +1,6 @@ use std::marker::PhantomData; -use api_models::{enums::FrmSuggestion, payments::PaymentsRejectRequest}; +use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest}; use async_trait::async_trait; use error_stack::ResultExt; use router_derive; @@ -24,24 +24,24 @@ use crate::{ }; #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] -#[operation(operations = "all", flow = "reject")] +#[operation(operations = "all", flow = "cancel")] pub struct PaymentReject; #[async_trait] impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> - GetTracker<F, PaymentData<F>, PaymentsRejectRequest, Ctx> for PaymentReject + GetTracker<F, PaymentData<F>, PaymentsCancelRequest, Ctx> for PaymentReject { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a AppState, payment_id: &api::PaymentIdType, - _request: &PaymentsRejectRequest, + _request: &PaymentsCancelRequest, _mandate_type: Option<api::MandateTransactionType>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, - ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsRejectRequest, Ctx>> { + ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, Ctx>> { let db = &*state.store; let merchant_id = &merchant_account.merchant_id; let storage_scheme = merchant_account.storage_scheme; @@ -57,6 +57,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> helpers::validate_payment_status_against_not_allowed_statuses( &payment_intent.status, &[ + enums::IntentStatus::Cancelled, enums::IntentStatus::Failed, enums::IntentStatus::Succeeded, enums::IntentStatus::Processing, @@ -176,7 +177,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> #[async_trait] impl<F: Clone, Ctx: PaymentMethodRetrieve> - UpdateTracker<F, PaymentData<F>, PaymentsRejectRequest, Ctx> for PaymentReject + UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest, Ctx> for PaymentReject { #[instrument(skip_all)] async fn update_trackers<'b>( @@ -190,7 +191,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> _should_decline_transaction: Option<FrmSuggestion>, _header_payload: api::HeaderPayload, ) -> RouterResult<( - BoxedOperation<'b, F, PaymentsRejectRequest, Ctx>, + BoxedOperation<'b, F, PaymentsCancelRequest, Ctx>, PaymentData<F>, )> where @@ -242,16 +243,16 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> } } -impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, PaymentsRejectRequest, Ctx> +impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, PaymentsCancelRequest, Ctx> for PaymentReject { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, - request: &PaymentsRejectRequest, + request: &PaymentsCancelRequest, merchant_account: &'a domain::MerchantAccount, ) -> RouterResult<( - BoxedOperation<'b, F, PaymentsRejectRequest, Ctx>, + BoxedOperation<'b, F, PaymentsCancelRequest, Ctx>, operations::ValidateResult<'a>, )> { Ok(( diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 9ab0b4f817f..e5552f0d156 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -512,113 +512,132 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( }; (capture_update, attempt_update) } - Ok(payments_response) => match payments_response { - types::PaymentsResponseData::PreProcessingResponse { - pre_processing_id, - connector_metadata, - connector_response_reference_id, - .. - } => { - let connector_transaction_id = match pre_processing_id.to_owned() { - types::PreprocessingResponseId::PreProcessingId(_) => None, - types::PreprocessingResponseId::ConnectorTransactionId(connector_txn_id) => { - Some(connector_txn_id) - } - }; - let preprocessing_step_id = match pre_processing_id { - types::PreprocessingResponseId::PreProcessingId(pre_processing_id) => { - Some(pre_processing_id) + Ok(payments_response) => { + let attempt_status = payment_data.payment_attempt.status.to_owned(); + let connector_status = router_data.status.to_owned(); + let updated_attempt_status = match ( + connector_status, + attempt_status, + payment_data.frm_message.to_owned(), + ) { + ( + enums::AttemptStatus::Authorized, + enums::AttemptStatus::Unresolved, + Some(frm_message), + ) => match frm_message.frm_status { + enums::FraudCheckStatus::Fraud | enums::FraudCheckStatus::ManualReview => { + attempt_status } - types::PreprocessingResponseId::ConnectorTransactionId(_) => None, - }; - let payment_attempt_update = storage::PaymentAttemptUpdate::PreprocessingUpdate { - status: router_data.get_attempt_status_for_db_update(&payment_data), - payment_method_id: Some(router_data.payment_method_id), + _ => router_data.get_attempt_status_for_db_update(&payment_data), + }, + _ => router_data.get_attempt_status_for_db_update(&payment_data), + }; + match payments_response { + types::PaymentsResponseData::PreProcessingResponse { + pre_processing_id, connector_metadata, - preprocessing_step_id, - connector_transaction_id, connector_response_reference_id, - updated_by: storage_scheme.to_string(), - }; - - (None, Some(payment_attempt_update)) - } - types::PaymentsResponseData::TransactionResponse { - resource_id, - redirection_data, - connector_metadata, - connector_response_reference_id, - incremental_authorization_allowed, - .. - } => { - payment_data - .payment_intent - .incremental_authorization_allowed = - core_utils::get_incremental_authorization_allowed_value( - incremental_authorization_allowed, - payment_data - .payment_intent - .request_incremental_authorization, - ); - let connector_transaction_id = match resource_id { - types::ResponseId::NoResponseId => None, - types::ResponseId::ConnectorTransactionId(id) - | types::ResponseId::EncodedData(id) => Some(id), - }; - - let encoded_data = payment_data.payment_attempt.encoded_data.clone(); - - let authentication_data = redirection_data - .map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data)) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Could not parse the connector response")?; - - // incase of success, update error code and error message - let error_status = if router_data.status == enums::AttemptStatus::Charged { - Some(None) - } else { - None - }; + .. + } => { + let connector_transaction_id = match pre_processing_id.to_owned() { + types::PreprocessingResponseId::PreProcessingId(_) => None, + types::PreprocessingResponseId::ConnectorTransactionId( + connector_txn_id, + ) => Some(connector_txn_id), + }; + let preprocessing_step_id = match pre_processing_id { + types::PreprocessingResponseId::PreProcessingId(pre_processing_id) => { + Some(pre_processing_id) + } + types::PreprocessingResponseId::ConnectorTransactionId(_) => None, + }; + let payment_attempt_update = + storage::PaymentAttemptUpdate::PreprocessingUpdate { + status: updated_attempt_status, + payment_method_id: Some(router_data.payment_method_id), + connector_metadata, + preprocessing_step_id, + connector_transaction_id, + connector_response_reference_id, + updated_by: storage_scheme.to_string(), + }; - if router_data.status == enums::AttemptStatus::Charged { - metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]); + (None, Some(payment_attempt_update)) } + types::PaymentsResponseData::TransactionResponse { + resource_id, + redirection_data, + connector_metadata, + connector_response_reference_id, + incremental_authorization_allowed, + .. + } => { + payment_data + .payment_intent + .incremental_authorization_allowed = + core_utils::get_incremental_authorization_allowed_value( + incremental_authorization_allowed, + payment_data + .payment_intent + .request_incremental_authorization, + ); + let connector_transaction_id = match resource_id { + types::ResponseId::NoResponseId => None, + types::ResponseId::ConnectorTransactionId(id) + | types::ResponseId::EncodedData(id) => Some(id), + }; - utils::add_apple_pay_payment_status_metrics( - router_data.status, - router_data.apple_pay_flow.clone(), - payment_data.payment_attempt.connector.clone(), - payment_data.payment_attempt.merchant_id.clone(), - ); + let encoded_data = payment_data.payment_attempt.encoded_data.clone(); - let (capture_updates, payment_attempt_update) = match payment_data - .multiple_capture_data - { - Some(multiple_capture_data) => { - let capture_update = storage::CaptureUpdate::ResponseUpdate { - status: enums::CaptureStatus::foreign_try_from(router_data.status)?, - connector_capture_id: connector_transaction_id.clone(), - connector_response_reference_id, - }; - let capture_update_list = vec![( - multiple_capture_data.get_latest_capture().clone(), - capture_update, - )]; - (Some((multiple_capture_data, capture_update_list)), None) + let authentication_data = redirection_data + .map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data)) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not parse the connector response")?; + + // incase of success, update error code and error message + let error_status = if router_data.status == enums::AttemptStatus::Charged { + Some(None) + } else { + None + }; + + if router_data.status == enums::AttemptStatus::Charged { + metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]); } - None => { - let status = router_data.get_attempt_status_for_db_update(&payment_data); - ( + + utils::add_apple_pay_payment_status_metrics( + router_data.status, + router_data.apple_pay_flow.clone(), + payment_data.payment_attempt.connector.clone(), + payment_data.payment_attempt.merchant_id.clone(), + ); + + let (capture_updates, payment_attempt_update) = match payment_data + .multiple_capture_data + { + Some(multiple_capture_data) => { + let capture_update = storage::CaptureUpdate::ResponseUpdate { + status: enums::CaptureStatus::foreign_try_from(router_data.status)?, + connector_capture_id: connector_transaction_id.clone(), + connector_response_reference_id, + }; + let capture_update_list = vec![( + multiple_capture_data.get_latest_capture().clone(), + capture_update, + )]; + (Some((multiple_capture_data, capture_update_list)), None) + } + None => ( None, Some(storage::PaymentAttemptUpdate::ResponseUpdate { - status, + status: updated_attempt_status, connector: None, connector_transaction_id: connector_transaction_id.clone(), authentication_type: None, amount_capturable: router_data .request - .get_amount_capturable(&payment_data, status), + .get_amount_capturable(&payment_data, updated_attempt_status), payment_method_id: Some(router_data.payment_method_id), mandate_id: payment_data .mandate_id @@ -636,56 +655,58 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( authentication_data, encoded_data, }), - ) - } - }; + ), + }; - (capture_updates, payment_attempt_update) - } - types::PaymentsResponseData::TransactionUnresolvedResponse { - resource_id, - reason, - connector_response_reference_id, - } => { - let connector_transaction_id = match resource_id { - types::ResponseId::NoResponseId => None, - types::ResponseId::ConnectorTransactionId(id) - | types::ResponseId::EncodedData(id) => Some(id), - }; - ( - None, - Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate { - status: router_data.get_attempt_status_for_db_update(&payment_data), - connector: None, - connector_transaction_id, - payment_method_id: Some(router_data.payment_method_id), - error_code: Some(reason.clone().map(|cd| cd.code)), - error_message: Some(reason.clone().map(|cd| cd.message)), - error_reason: Some(reason.map(|cd| cd.message)), - connector_response_reference_id, - updated_by: storage_scheme.to_string(), - }), - ) - } - types::PaymentsResponseData::SessionResponse { .. } => (None, None), - types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None), - types::PaymentsResponseData::TokenizationResponse { .. } => (None, None), - types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None), - types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None), - types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => (None, None), - types::PaymentsResponseData::MultipleCaptureResponse { - capture_sync_response_list, - } => match payment_data.multiple_capture_data { - Some(multiple_capture_data) => { - let capture_update_list = response_to_capture_update( - &multiple_capture_data, - capture_sync_response_list, - )?; - (Some((multiple_capture_data, capture_update_list)), None) + (capture_updates, payment_attempt_update) } - None => (None, None), - }, - }, + types::PaymentsResponseData::TransactionUnresolvedResponse { + resource_id, + reason, + connector_response_reference_id, + } => { + let connector_transaction_id = match resource_id { + types::ResponseId::NoResponseId => None, + types::ResponseId::ConnectorTransactionId(id) + | types::ResponseId::EncodedData(id) => Some(id), + }; + ( + None, + Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate { + status: updated_attempt_status, + connector: None, + connector_transaction_id, + payment_method_id: Some(router_data.payment_method_id), + error_code: Some(reason.clone().map(|cd| cd.code)), + error_message: Some(reason.clone().map(|cd| cd.message)), + error_reason: Some(reason.map(|cd| cd.message)), + connector_response_reference_id, + updated_by: storage_scheme.to_string(), + }), + ) + } + types::PaymentsResponseData::SessionResponse { .. } => (None, None), + types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None), + types::PaymentsResponseData::TokenizationResponse { .. } => (None, None), + types::PaymentsResponseData::ConnectorCustomerResponse { .. } => (None, None), + types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => (None, None), + types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => { + (None, None) + } + types::PaymentsResponseData::MultipleCaptureResponse { + capture_sync_response_list, + } => match payment_data.multiple_capture_data { + Some(multiple_capture_data) => { + let capture_update_list = response_to_capture_update( + &multiple_capture_data, + capture_sync_response_list, + )?; + (Some((multiple_capture_data, capture_update_list)), None) + } + None => (None, None), + }, + } + } }; payment_data.multiple_capture_data = match capture_update { Some((mut multiple_capture_data, capture_updates)) => { diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index 0fd45c5af3b..8d74eb3fa96 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -40,6 +40,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, Ctx>( customer: &Option<domain::Customer>, validate_result: &operations::ValidateResult<'_>, schedule_time: Option<time::PrimitiveDateTime>, + frm_suggestion: Option<storage_enums::FrmSuggestion>, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, @@ -90,6 +91,7 @@ where validate_result, schedule_time, true, + frm_suggestion, ) .await?; } @@ -133,6 +135,7 @@ where schedule_time, //this is an auto retry payment, but not step-up false, + frm_suggestion, ) .await?; @@ -275,6 +278,7 @@ pub async fn do_retry<F, ApiRequest, FData, Ctx>( validate_result: &operations::ValidateResult<'_>, schedule_time: Option<time::PrimitiveDateTime>, is_step_up: bool, + frm_suggestion: Option<storage_enums::FrmSuggestion>, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, @@ -310,6 +314,7 @@ where validate_result, schedule_time, api::HeaderPayload::default(), + frm_suggestion, ) .await } diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 34f41c49cdd..379cd4f2f1f 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -968,7 +968,7 @@ pub async fn payments_approve( payload.clone(), |state, auth, req| { payments::payments_core::< - api_types::Authorize, + api_types::Capture, payment_types::PaymentsResponse, _, _, @@ -979,10 +979,8 @@ pub async fn payments_approve( auth.merchant_account, auth.key_store, payments::PaymentApprove, - payment_types::PaymentsRequest { - payment_id: Some(payment_types::PaymentIdType::PaymentIntentId( - req.payment_id, - )), + payment_types::PaymentsCaptureRequest { + payment_id: req.payment_id, ..Default::default() }, api::AuthFlow::Merchant, @@ -1030,7 +1028,7 @@ pub async fn payments_reject( payload.clone(), |state, auth, req| { payments::payments_core::< - api_types::Reject, + api_types::Void, payment_types::PaymentsResponse, _, _, @@ -1041,7 +1039,11 @@ pub async fn payments_reject( auth.merchant_account, auth.key_store, payments::PaymentReject, - req, + payment_types::PaymentsCancelRequest { + payment_id: req.payment_id, + cancellation_reason: Some("Rejected by merchant".to_string()), + ..Default::default() + }, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None,
2023-12-20T09:15:53Z
## Description #3175 ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
1bbd9d5df0f145f192d0271d89761488e7347989
Tested locally using postman collection https://galactic-capsule-229427.postman.co/workspace/My-Workspace~2b563e0d-bad3-420f-8c0b-0fd5b278a4fe/collection/9906252-e8ad195c-90f5-4527-a40b-1a25bc9bedd2?action=share&creator=9906252 **Test Cases** - Payments <> FRM manual flow (pre + post) - Approve + Rejection should be working
[ "crates/router/src/core/fraud_check.rs", "crates/router/src/core/payments.rs", "crates/router/src/core/payments/operations/payment_approve.rs", "crates/router/src/core/payments/operations/payment_reject.rs", "crates/router/src/core/payments/operations/payment_response.rs", "crates/router/src/core/payments...
juspay/hyperswitch
juspay__hyperswitch-2899
Bug: [BUG]: MCA metadata deserialization failures should be 4xx ### :memo: Feature Description - We don't have validation for Merchant Connector Account metadata, So while creating MCA we are allowing any json value. Because of which RequestEncodingFailure happening during payments for the MCA which doesn't have the expected fields. - Recreating scenario : Create a merchant connector account for coinbase with empty metadata .It doesn't throw error as we don't have metadata validation for coinbase . If you try to make payment now this will throw deserilization error for `CoinbaseConnectorMeta` which is merchant connector metadata for coinbase . ### :hammer: Possible Implementation - In the event of a deserialization failure of MCA metadata during payments and refunds, convert the ParsingFailed error to ConnectorError::InvalidConnectorConfig. - We already have authType validation in core/admin.rs , we need similar validation for connector metadata for coinbase . - Make sure that the config field in ConnectorError::InvalidConnectorConfig specifies the invalid configuration name. - Note that the ConnectorError::InvalidConnectorConfig error is already associated with [HTTP 400](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400) in the core. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2746 :bookmark: Note: All the changes needed should be contained within `/hyperswitch_oss/crates/router/src/connector/utils.rs` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs index ce9bb3e871c..b1435e50df9 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/router/src/connector/coinbase/transformers.rs @@ -1,5 +1,7 @@ use std::collections::HashMap; +use common_utils::pii; +use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use crate::{ @@ -250,6 +252,14 @@ pub struct CoinbaseConnectorMeta { pub pricing_type: String, } +impl TryFrom<&Option<pii::SecretSerdeValue>> for CoinbaseConnectorMeta { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> { + utils::to_connector_meta_from_secret(meta_data.clone()) + .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" }) + } +} + fn get_crypto_specific_payment_data( item: &types::PaymentsAuthorizeRouterData, ) -> Result<CoinbasePaymentsRequest, error_stack::Report<errors::ConnectorError>> { @@ -260,11 +270,10 @@ fn get_crypto_specific_payment_data( let name = billing_address.and_then(|add| add.get_first_name().ok().map(|name| name.to_owned())); let description = item.get_description().ok(); - let connector_meta: CoinbaseConnectorMeta = - utils::to_connector_meta_from_secret_with_required_field( - item.connector_meta_data.clone(), - "Pricing Type Not present in connector meta data", - )?; + let connector_meta = CoinbaseConnectorMeta::try_from(&item.connector_meta_data) + .change_context(errors::ConnectorError::InvalidConnectorConfig { + config: "Merchant connector account metadata", + })?; let pricing_type = connector_meta.pricing_type; let local_price = get_local_price(item); let redirect_url = item.request.get_return_url()?; diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 8f028e37a9e..9df11a6dd14 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1198,23 +1198,6 @@ where json.parse_value(std::any::type_name::<T>()).switch() } -pub fn to_connector_meta_from_secret_with_required_field<T>( - connector_meta: Option<Secret<serde_json::Value>>, - error_message: &'static str, -) -> Result<T, Error> -where - T: serde::de::DeserializeOwned, -{ - let connector_error = errors::ConnectorError::MissingRequiredField { - field_name: error_message, - }; - let parsed_meta = to_connector_meta_from_secret(connector_meta).ok(); - match parsed_meta { - Some(meta) => Ok(meta), - _ => Err(connector_error.into()), - } -} - pub fn to_connector_meta_from_secret<T>( connector_meta: Option<Secret<serde_json::Value>>, ) -> Result<T, Error> diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index fd4cae3a2b9..364c5b9b212 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1713,9 +1713,9 @@ pub(crate) fn validate_auth_and_metadata_type( checkout::transformers::CheckoutAuthType::try_from(val)?; Ok(()) } - api_enums::Connector::Coinbase => { coinbase::transformers::CoinbaseAuthType::try_from(val)?; + coinbase::transformers::CoinbaseConnectorMeta::try_from(connector_meta_data)?; Ok(()) } api_enums::Connector::Cryptopay => {
2023-12-19T12:53:56Z
## Description <!-- Describe your changes in detail --> I've removed `to_connector_meta_from_secret_with_required_field`, which uses `MissingRequiredField` as an error (I also didn't like the unnecessary initialization of the `MissingRequiredField` before we knew if it would be needed). Instead, I added a `TryFrom` implementation for `CoinbaseConnectorMeta`, which uses the requested `ConnectorError::InvalidConnectorConfig`. Additionally, I included `CoinbaseConnectorMeta::try_from` in the `validate_auth_and_metadata_type` as suggested. ### Migration ``` -- The migration is for adding an empty `pricing_type` attribute for `CoinbaseConnectorMeta` where it is missing. UPDATE merchant_connector_account SET metadata = jsonb_insert( metadata, '{pricing_type}', '""', true ) WHERE connector_name = 'coinbase' AND NOT metadata ? 'pricing_type'; ``` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This PR addresses the bug from the issue: https://github.com/juspay/hyperswitch/issues/2899. # ### Migration script test https://onecompiler.com/postgresql/3zz2tpkad **Test script with test data and run migration:** ```label=dsa CREATE TABLE merchant_connector_account ( id SERIAL PRIMARY KEY, connector_name VARCHAR(255) NOT NULL ); ALTER TABLE merchant_connector_account ADD COLUMN metadata JSONB DEFAULT NULL; -- insert test data INSERT INTO merchant_connector_account ( id, connector_name, metadata ) VALUES (1, 'coinbase', '{ "pricing_type": "fixed-rate" }'), (2, 'coinbase', '{ "whatever_attribute": "abc" }'), (3, 'coinbase', '{}'); -- Before select * from merchant_connector_account; -- Run migration: -- The migration is for adding an empty `pricing_type` attribute for `CoinbaseConnectorMeta` where it is missing. UPDATE merchant_connector_account SET metadata = jsonb_insert( metadata, '{pricing_type}', '""', true ) WHERE connector_name = 'coinbase' AND NOT metadata ? 'pricing_type'; -- After select * from merchant_connector_account; ``` **Output:** ``` Output: CREATE TABLE ALTER TABLE INSERT 0 3 id | connector_name | metadata ----+----------------+-------------------------------- 1 | coinbase | {"pricing_type": "fixed-rate"} 2 | coinbase | {"whatever_attribute": "abc"} 3 | coinbase | {} (3 rows) UPDATE 2 id | connector_name | metadata ----+----------------+--------------------------------------------------- 1 | coinbase | {"pricing_type": "fixed-rate"} 2 | coinbase | {"pricing_type": "", "whatever_attribute": "abc"} 3 | coinbase | {"pricing_type": ""} (3 rows) ``` **Run locally:** **Invalid metadata:** ![image](https://github.com/juspay/hyperswitch/assets/8159517/5e087dad-9dab-4441-a444-787d8e720c1a) **Empty metadata:** ![image](https://github.com/juspay/hyperswitch/assets/8159517/0f745195-0b0b-4276-aeba-c18ad11d3749) **Correct metadata:** ![image](https://github.com/juspay/hyperswitch/assets/8159517/a5fe8ffa-12d2-449d-8363-a214aadca2fb)
5a791aaf4dc05e8ffdb60464a03b6fc41f860581
**Run unit test:** ``` cargo test --release --package router --lib connector::coinbase::transformers::tests::coinbase_payments_request_try_from_works -- --exact ``` ![image](https://github.com/juspay/hyperswitch/assets/8159517/a296af9b-a454-4d9b-a8ad-1939a837f04b) ### Migration script test https://onecompiler.com/postgresql/3zz2tpkad **Test script with test data and run migration:** ```label=dsa CREATE TABLE merchant_connector_account ( id SERIAL PRIMARY KEY, connector_name VARCHAR(255) NOT NULL ); ALTER TABLE merchant_connector_account ADD COLUMN metadata JSONB DEFAULT NULL; -- insert test data INSERT INTO merchant_connector_account ( id, connector_name, metadata ) VALUES (1, 'coinbase', '{ "pricing_type": "fixed-rate" }'), (2, 'coinbase', '{ "whatever_attribute": "abc" }'), (3, 'coinbase', '{}'); -- Before select * from merchant_connector_account; -- Run migration: -- The migration is for adding an empty `pricing_type` attribute for `CoinbaseConnectorMeta` where it is missing. UPDATE merchant_connector_account SET metadata = jsonb_insert( metadata, '{pricing_type}', '""', true ) WHERE connector_name = 'coinbase' AND NOT metadata ? 'pricing_type'; -- After select * from merchant_connector_account; ``` **Output:** ``` Output: CREATE TABLE ALTER TABLE INSERT 0 3 id | connector_name | metadata ----+----------------+-------------------------------- 1 | coinbase | {"pricing_type": "fixed-rate"} 2 | coinbase | {"whatever_attribute": "abc"} 3 | coinbase | {} (3 rows) UPDATE 2 id | connector_name | metadata ----+----------------+--------------------------------------------------- 1 | coinbase | {"pricing_type": "fixed-rate"} 2 | coinbase | {"pricing_type": "", "whatever_attribute": "abc"} 3 | coinbase | {"pricing_type": ""} (3 rows) ``` **Run locally:** **Invalid metadata:** ![image](https://github.com/juspay/hyperswitch/assets/8159517/5e087dad-9dab-4441-a444-787d8e720c1a) **Empty metadata:** ![image](https://github.com/juspay/hyperswitch/assets/8159517/0f745195-0b0b-4276-aeba-c18ad11d3749) **Correct metadata:** ![image](https://github.com/juspay/hyperswitch/assets/8159517/a5fe8ffa-12d2-449d-8363-a214aadca2fb)
[ "crates/router/src/connector/coinbase/transformers.rs", "crates/router/src/connector/utils.rs", "crates/router/src/core/admin.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3154
Bug: [FEATURE]: [VOLT] Add Support for Webhooks ### Feature Description Adding Support for Payment Webhooks for Volt Connector ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/volt.rs b/crates/router/src/connector/volt.rs index bf36a7bff61..3641c0c3ddc 100644 --- a/crates/router/src/connector/volt.rs +++ b/crates/router/src/connector/volt.rs @@ -2,11 +2,13 @@ pub mod transformers; use std::fmt::Debug; -use common_utils::request::RequestContent; +use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; use error_stack::{IntoReport, ResultExt}; use masking::{ExposeInterface, PeekInterface}; use transformers as volt; +use self::transformers::webhook_headers; +use super::utils; use crate::{ configs::settings, core::errors::{self, CustomResult}, @@ -398,7 +400,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe data: &types::PaymentsSyncRouterData, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - let response: volt::VoltPsyncResponse = res + let response: volt::VoltPaymentsResponseData = res .response .parse_struct("volt PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -586,24 +588,93 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse #[async_trait::async_trait] impl api::IncomingWebhook for Volt { - fn get_webhook_object_reference_id( + fn get_webhook_source_verification_algorithm( &self, _request: &api::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::HmacSha256)) + } + + fn get_webhook_source_verification_signature( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let signature = + utils::get_header_key_value(webhook_headers::X_VOLT_SIGNED, request.headers) + .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; + + hex::decode(signature) + .into_report() + .change_context(errors::ConnectorError::WebhookVerificationSecretInvalid) + } + + fn get_webhook_source_verification_message( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, + _merchant_id: &str, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let x_volt_timed = + utils::get_header_key_value(webhook_headers::X_VOLT_TIMED, request.headers)?; + let user_agent = utils::get_header_key_value(webhook_headers::USER_AGENT, request.headers)?; + let version = user_agent + .split('/') + .last() + .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; + Ok(format!( + "{}|{}|{}", + String::from_utf8_lossy(request.body), + x_volt_timed, + version + ) + .into_bytes()) + } + + fn get_webhook_object_reference_id( + &self, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let webhook_body: volt::VoltWebhookBodyReference = request + .body + .parse_struct("VoltWebhookBodyReference") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + let reference = match webhook_body.merchant_internal_reference { + Some(merchant_internal_reference) => { + api_models::payments::PaymentIdType::PaymentAttemptId(merchant_internal_reference) + } + None => { + api_models::payments::PaymentIdType::ConnectorTransactionId(webhook_body.payment) + } + }; + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + reference, + )) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + if request.body.is_empty() { + Ok(api::IncomingWebhookEvent::EndpointVerification) + } else { + let payload: volt::VoltWebhookBodyEventType = request + .body + .parse_struct("VoltWebhookBodyEventType") + .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; + Ok(api::IncomingWebhookEvent::from(payload.status)) + } } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() + let details: volt::VoltWebhookObjectResource = request + .body + .parse_struct("VoltWebhookObjectResource") + .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; + Ok(Box::new(details)) } } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index 9ee2a3f012e..4c6eaeb52f4 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{self, AddressDetailsData, RouterData}, + consts, core::errors, services, types::{self, api, storage::enums as storage_enums}, @@ -41,6 +42,12 @@ impl<T> } } +pub mod webhook_headers { + pub const X_VOLT_SIGNED: &str = "X-Volt-Signed"; + pub const X_VOLT_TIMED: &str = "X-Volt-Timed"; + pub const USER_AGENT: &str = "User-Agent"; +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct VoltPaymentsRequest { @@ -50,7 +57,6 @@ pub struct VoltPaymentsRequest { transaction_type: TransactionType, merchant_internal_reference: String, shopper: ShopperDetails, - notification_url: Option<String>, payment_success_url: Option<String>, payment_failure_url: Option<String>, payment_pending_url: Option<String>, @@ -91,7 +97,6 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme let payment_failure_url = item.router_data.request.router_return_url.clone(); let payment_pending_url = item.router_data.request.router_return_url.clone(); let payment_cancel_url = item.router_data.request.router_return_url.clone(); - let notification_url = item.router_data.request.webhook_url.clone(); let address = item.router_data.get_billing_address()?; let shopper = ShopperDetails { email: item.router_data.request.email.clone(), @@ -109,7 +114,6 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme payment_failure_url, payment_pending_url, payment_cancel_url, - notification_url, shopper, transaction_type, }) @@ -291,8 +295,9 @@ impl<F, T> } } -#[derive(Debug, Deserialize)] +#[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[derive(strum::Display)] pub enum VoltPaymentStatus { NewPayment, Completed, @@ -309,7 +314,15 @@ pub enum VoltPaymentStatus { Failed, Settled, } -#[derive(Debug, Deserialize)] + +#[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum VoltPaymentsResponseData { + WebhookResponse(VoltWebhookObjectResource), + PsyncResponse(VoltPsyncResponse), +} + +#[derive(Debug, Serialize, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VoltPsyncResponse { status: VoltPaymentStatus, @@ -317,29 +330,102 @@ pub struct VoltPsyncResponse { merchant_internal_reference: Option<String>, } -impl<F, T> TryFrom<types::ResponseRouterData<F, VoltPsyncResponse, T, types::PaymentsResponseData>> +impl<F, T> + TryFrom<types::ResponseRouterData<F, VoltPaymentsResponseData, T, types::PaymentsResponseData>> for types::RouterData<F, T, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, VoltPsyncResponse, T, types::PaymentsResponseData>, + item: types::ResponseRouterData< + F, + VoltPaymentsResponseData, + T, + types::PaymentsResponseData, + >, ) -> Result<Self, Self::Error> { - Ok(Self { - status: enums::AttemptStatus::from(item.response.status), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: item - .response - .merchant_internal_reference - .or(Some(item.response.id)), - incremental_authorization_allowed: None, - }), - ..item.data - }) + match item.response { + VoltPaymentsResponseData::PsyncResponse(payment_response) => { + let status = enums::AttemptStatus::from(payment_response.status.clone()); + Ok(Self { + status, + response: if is_payment_failure(status) { + Err(types::ErrorResponse { + code: payment_response.status.clone().to_string(), + message: payment_response.status.clone().to_string(), + reason: Some(payment_response.status.to_string()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(payment_response.id), + }) + } else { + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + payment_response.id.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: payment_response + .merchant_internal_reference + .or(Some(payment_response.id)), + incremental_authorization_allowed: None, + }) + }, + ..item.data + }) + } + VoltPaymentsResponseData::WebhookResponse(webhook_response) => { + let detailed_status = webhook_response.detailed_status.clone(); + let status = enums::AttemptStatus::from(webhook_response.status); + Ok(Self { + status, + response: if is_payment_failure(status) { + Err(types::ErrorResponse { + code: detailed_status + .clone() + .map(|volt_status| volt_status.to_string()) + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_owned()), + message: detailed_status + .clone() + .map(|volt_status| volt_status.to_string()) + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_owned()), + reason: detailed_status + .clone() + .map(|volt_status| volt_status.to_string()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: Some(webhook_response.payment.clone()), + }) + } else { + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + webhook_response.payment.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: webhook_response + .merchant_internal_reference + .or(Some(webhook_response.payment)), + incremental_authorization_allowed: None, + }) + }, + ..item.data + }) + } + } + } +} + +impl From<VoltWebhookStatus> for enums::AttemptStatus { + fn from(status: VoltWebhookStatus) -> Self { + match status { + VoltWebhookStatus::Completed | VoltWebhookStatus::Received => Self::Charged, + VoltWebhookStatus::Failed | VoltWebhookStatus::NotReceived => Self::Failure, + VoltWebhookStatus::Pending => Self::Pending, + } } } @@ -405,6 +491,68 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } +#[derive(Debug, Deserialize, Clone, Serialize)] +pub struct VoltWebhookBodyReference { + pub payment: String, + pub merchant_internal_reference: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct VoltWebhookBodyEventType { + pub status: VoltWebhookStatus, + pub detailed_status: Option<VoltDetailedStatus>, +} + +#[derive(Debug, Deserialize, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct VoltWebhookObjectResource { + pub payment: String, + pub merchant_internal_reference: Option<String>, + pub status: VoltWebhookStatus, + pub detailed_status: Option<VoltDetailedStatus>, +} + +#[derive(Debug, Deserialize, Clone, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum VoltWebhookStatus { + Completed, + Failed, + Pending, + Received, + NotReceived, +} + +#[derive(Debug, Deserialize, Clone, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[derive(strum::Display)] +pub enum VoltDetailedStatus { + RefusedByRisk, + RefusedByBank, + ErrorAtBank, + CancelledByUser, + AbandonedByUser, + Failed, + Completed, + BankRedirect, + DelayedAtBank, + AwaitingCheckoutAuthorisation, +} + +impl From<VoltWebhookStatus> for api::IncomingWebhookEvent { + fn from(status: VoltWebhookStatus) -> Self { + match status { + VoltWebhookStatus::Completed | VoltWebhookStatus::Received => { + Self::PaymentIntentSuccess + } + VoltWebhookStatus::Failed | VoltWebhookStatus::NotReceived => { + Self::PaymentIntentFailure + } + VoltWebhookStatus::Pending => Self::PaymentIntentProcessing, + } + } +} + #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct VoltErrorResponse { pub exception: VoltErrorException, @@ -429,3 +577,32 @@ pub struct VoltErrorList { pub property: String, pub message: String, } + +fn is_payment_failure(status: enums::AttemptStatus) -> bool { + match status { + common_enums::AttemptStatus::AuthenticationFailed + | common_enums::AttemptStatus::AuthorizationFailed + | common_enums::AttemptStatus::CaptureFailed + | common_enums::AttemptStatus::VoidFailed + | common_enums::AttemptStatus::Failure => true, + common_enums::AttemptStatus::Started + | common_enums::AttemptStatus::RouterDeclined + | common_enums::AttemptStatus::AuthenticationPending + | common_enums::AttemptStatus::AuthenticationSuccessful + | common_enums::AttemptStatus::Authorized + | common_enums::AttemptStatus::Charged + | common_enums::AttemptStatus::Authorizing + | common_enums::AttemptStatus::CodInitiated + | common_enums::AttemptStatus::Voided + | common_enums::AttemptStatus::VoidInitiated + | common_enums::AttemptStatus::CaptureInitiated + | common_enums::AttemptStatus::AutoRefunded + | common_enums::AttemptStatus::PartialCharged + | common_enums::AttemptStatus::PartialChargedAndChargeable + | common_enums::AttemptStatus::Unresolved + | common_enums::AttemptStatus::Pending + | common_enums::AttemptStatus::PaymentMethodAwaited + | common_enums::AttemptStatus::ConfirmationAwaited + | common_enums::AttemptStatus::DeviceDataCollectionPending => false, + } +}
2023-12-17T18:47:23Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
252443a50dc48939eb08b3bcd67273bb71bbe349
![Screenshot 2024-01-03 at 8 28 35 PM 2](https://github.com/juspay/hyperswitch/assets/85639103/e2a0a038-6b92-4319-a94b-a57d976b205b) ```json { "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "bank_redirect", "payment_method_type": "open_banking_uk", "payment_method_data": { "bank_redirect": { "open_banking_uk": { } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "business_label": "food", "business_country": "US" } ```
[ "crates/router/src/connector/volt.rs", "crates/router/src/connector/volt/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3044
Bug: [FEATURE] Implement `AuthorizationInterface` for `MockDb` Spin off from https://github.com/juspay/hyperswitch/issues/172. Refer to the parent issue for more information
diff --git a/crates/diesel_models/src/authorization.rs b/crates/diesel_models/src/authorization.rs index 64fd1c65187..b6f75bbb9b7 100644 --- a/crates/diesel_models/src/authorization.rs +++ b/crates/diesel_models/src/authorization.rs @@ -57,6 +57,21 @@ pub struct AuthorizationUpdateInternal { pub connector_authorization_id: Option<String>, } +impl AuthorizationUpdateInternal { + pub fn create_authorization(self, source: Authorization) -> Authorization { + Authorization { + status: self.status.unwrap_or(source.status), + error_code: self.error_code.or(source.error_code), + error_message: self.error_message.or(source.error_message), + modified_at: self.modified_at.unwrap_or(common_utils::date_time::now()), + connector_authorization_id: self + .connector_authorization_id + .or(source.connector_authorization_id), + ..source + } + } +} + impl From<AuthorizationUpdate> for AuthorizationUpdateInternal { fn from(authorization_child_update: AuthorizationUpdate) -> Self { let now = Some(common_utils::date_time::now()); diff --git a/crates/router/src/db/authorization.rs b/crates/router/src/db/authorization.rs index f24daaf718a..d167d177537 100644 --- a/crates/router/src/db/authorization.rs +++ b/crates/router/src/db/authorization.rs @@ -1,3 +1,4 @@ +use diesel_models::authorization::AuthorizationUpdateInternal; use error_stack::IntoReport; use super::{MockDb, Store}; @@ -77,28 +78,71 @@ impl AuthorizationInterface for Store { impl AuthorizationInterface for MockDb { async fn insert_authorization( &self, - _authorization: storage::AuthorizationNew, + authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut authorizations = self.authorizations.lock().await; + if authorizations.iter().any(|authorization_inner| { + authorization_inner.authorization_id == authorization.authorization_id + }) { + Err(errors::StorageError::DuplicateValue { + entity: "authorization_id", + key: None, + })? + } + let authorization = storage::Authorization { + authorization_id: authorization.authorization_id, + merchant_id: authorization.merchant_id, + payment_id: authorization.payment_id, + amount: authorization.amount, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + status: authorization.status, + error_code: authorization.error_code, + error_message: authorization.error_message, + connector_authorization_id: authorization.connector_authorization_id, + previously_authorized_amount: authorization.previously_authorized_amount, + }; + authorizations.push(authorization.clone()); + Ok(authorization) } async fn find_all_authorizations_by_merchant_id_payment_id( &self, - _merchant_id: &str, - _payment_id: &str, + merchant_id: &str, + payment_id: &str, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let authorizations = self.authorizations.lock().await; + let authorizations_found: Vec<storage::Authorization> = authorizations + .iter() + .filter(|a| a.merchant_id == merchant_id && a.payment_id == payment_id) + .cloned() + .collect(); + + Ok(authorizations_found) } async fn update_authorization_by_merchant_id_authorization_id( &self, - _merchant_id: String, - _authorization_id: String, - _authorization: storage::AuthorizationUpdate, + merchant_id: String, + authorization_id: String, + authorization_update: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { - // TODO: Implement function for `MockDb` - Err(errors::StorageError::MockDbError)? + let mut authorizations = self.authorizations.lock().await; + authorizations + .iter_mut() + .find(|authorization| authorization.authorization_id == authorization_id && authorization.merchant_id == merchant_id) + .map(|authorization| { + let authorization_updated = + AuthorizationUpdateInternal::from(authorization_update) + .create_authorization(authorization.clone()); + *authorization = authorization_updated.clone(); + authorization_updated + }) + .ok_or( + errors::StorageError::ValueNotFound(format!( + "cannot find authorization for authorization_id = {authorization_id} and merchant_id = {merchant_id}" + )) + .into(), + ) } } diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index e22d39ce70c..a6ba763bd91 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -43,6 +43,7 @@ pub struct MockDb { pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>, pub users: Arc<Mutex<Vec<store::user::User>>>, pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>, + pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>, pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>, } @@ -79,6 +80,7 @@ impl MockDb { organizations: Default::default(), users: Default::default(), user_roles: Default::default(), + authorizations: Default::default(), dashboard_metadata: Default::default(), }) }
2023-12-16T23:57:21Z
## Description Implement AuthorizationInterface for MockDb ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
dc0e40d54bcff26c9996db6adc0a6071dc37ded0
[ "crates/diesel_models/src/authorization.rs", "crates/router/src/db/authorization.rs", "crates/storage_impl/src/mock_db.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3147
Bug: [REFACTOR] Handle card duplication ### Feature Description Currently card duplication and card metadata (card_holder_name, expiry year, expiry month, etc) changes are not being handled in Hyperswitch. ### Possible Implementation Rust locker sends `duplication_check` status in its store card response. Based on this response, duplication has to be handled ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 7b505e7c01c..dfbd9211dfb 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -109,7 +109,10 @@ pub fn store_default_payment_method( req: &api::PaymentMethodCreate, customer_id: &str, merchant_id: &String, -) -> (api::PaymentMethodResponse, bool) { +) -> ( + api::PaymentMethodResponse, + Option<payment_methods::DataDuplicationCheck>, +) { let pm_id = generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.to_string(), @@ -125,7 +128,7 @@ pub fn store_default_payment_method( installment_payment_enabled: false, //[#219] payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] }; - (payment_method_response, false) + (payment_method_response, None) } #[instrument(skip_all)] @@ -136,6 +139,7 @@ pub async fn add_payment_method( key_store: &domain::MerchantKeyStore, ) -> errors::RouterResponse<api::PaymentMethodResponse> { req.validate()?; + let db = &*state.store; let merchant_id = &merchant_account.merchant_id; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; @@ -178,34 +182,179 @@ pub async fn add_payment_method( )), }; - let (resp, is_duplicate) = response?; - if !is_duplicate { - let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); + let (resp, duplication_check) = response?; + + match duplication_check { + Some(duplication_check) => match duplication_check { + payment_methods::DataDuplicationCheck::Duplicated => { + let existing_pm = db.find_payment_method(&resp.payment_method_id).await; + + if let Err(err) = existing_pm { + if err.current_context().is_db_not_found() { + insert_payment_method( + db, + &resp, + req, + key_store, + merchant_id, + &customer_id, + None, + ) + .await + } else { + Err(err) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while finding payment method") + }? + }; + } - let pm_card_details = resp - .card - .as_ref() - .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + payment_methods::DataDuplicationCheck::MetaDataChanged => { + if let Some(card) = req.card.clone() { + delete_card_from_locker( + &state, + &customer_id, + merchant_id, + &resp.payment_method_id, + ) + .await?; + + let add_card_resp = add_card_hs( + &state, + req.clone(), + &card, + customer_id.clone(), + merchant_account, + api::enums::LockerChoice::Tartarus, + Some(&resp.payment_method_id), + ) + .await; - let pm_data_encrypted = - create_encrypted_payment_method_data(key_store, pm_card_details).await; + if let Err(err) = add_card_resp { + logger::error!(vault_err=?err); + db.delete_payment_method_by_merchant_id_payment_method_id( + merchant_id, + &resp.payment_method_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; - create_payment_method( - &*state.store, - &req, - &customer_id, - &resp.payment_method_id, - &resp.merchant_id, - pm_metadata.cloned(), - pm_data_encrypted, - key_store, - ) - .await?; - } + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while updating card metadata changes"))? + }; + + let existing_pm = db.find_payment_method(&resp.payment_method_id).await; + match existing_pm { + Ok(pm) => { + let updated_card = Some(api::CardDetailFromLocker { + scheme: None, + last4_digits: Some( + card.card_number + .to_string() + .split_off(card.card_number.to_string().len() - 4), + ), + issuer_country: None, + card_number: Some(card.card_number), + expiry_month: Some(card.card_exp_month), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_network: None, + card_isin: None, + card_issuer: None, + card_type: None, + saved_to_locker: true, + }); + + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card(CardDetailsPaymentMethod::from( + card.clone(), + )) + }); + let pm_data_encrypted = + create_encrypted_payment_method_data(key_store, updated_pmd).await; + + let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: pm_data_encrypted, + }; + + db.update_payment_method(pm, pm_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; + } + Err(err) => { + if err.current_context().is_db_not_found() { + insert_payment_method( + db, + &resp, + req, + key_store, + merchant_id, + &customer_id, + None, + ) + .await + } else { + Err(err) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while finding payment method") + }?; + } + } + } + } + }, + None => { + let pm_metadata = resp.metadata.as_ref().map(|data| data.peek()); + + insert_payment_method( + db, + &resp, + req, + key_store, + merchant_id, + &customer_id, + pm_metadata.cloned(), + ) + .await?; + } + }; Ok(services::ApplicationResponse::Json(resp)) } +pub async fn insert_payment_method( + db: &dyn db::StorageInterface, + resp: &api::PaymentMethodResponse, + req: api::PaymentMethodCreate, + key_store: &domain::MerchantKeyStore, + merchant_id: &str, + customer_id: &str, + pm_metadata: Option<serde_json::Value>, +) -> errors::RouterResult<()> { + let pm_card_details = resp + .card + .as_ref() + .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))); + let pm_data_encrypted = create_encrypted_payment_method_data(key_store, pm_card_details).await; + create_payment_method( + db, + &req, + customer_id, + &resp.payment_method_id, + merchant_id, + pm_metadata, + pm_data_encrypted, + key_store, + ) + .await?; + + Ok(()) +} + #[instrument(skip_all)] pub async fn update_customer_payment_method( state: routes::AppState, @@ -264,7 +413,13 @@ pub async fn add_bank_to_locker( key_store: &domain::MerchantKeyStore, bank: &api::BankPayout, customer_id: &String, -) -> errors::CustomResult<(api::PaymentMethodResponse, bool), errors::VaultError> { +) -> errors::CustomResult< + ( + api::PaymentMethodResponse, + Option<payment_methods::DataDuplicationCheck>, + ), + errors::VaultError, +> { let key = key_store.key.get_inner().peek(); let payout_method_data = api::PayoutMethodData::Bank(bank.clone()); let enc_data = async { @@ -312,7 +467,7 @@ pub async fn add_bank_to_locker( req, &merchant_account.merchant_id, ); - Ok((payment_method_resp, store_resp.duplicate.unwrap_or(false))) + Ok((payment_method_resp, store_resp.duplication_check)) } /// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method @@ -322,7 +477,13 @@ pub async fn add_card_to_locker( card: &api::CardDetail, customer_id: &String, merchant_account: &domain::MerchantAccount, -) -> errors::CustomResult<(api::PaymentMethodResponse, bool), errors::VaultError> { +) -> errors::CustomResult< + ( + api::PaymentMethodResponse, + Option<payment_methods::DataDuplicationCheck>, + ), + errors::VaultError, +> { metrics::STORED_TO_LOCKER.add(&metrics::CONTEXT, 1, &[]); let add_card_to_hs_resp = request::record_operation_time( async { @@ -540,7 +701,13 @@ pub async fn add_card_hs( merchant_account: &domain::MerchantAccount, locker_choice: api_enums::LockerChoice, card_reference: Option<&str>, -) -> errors::CustomResult<(api::PaymentMethodResponse, bool), errors::VaultError> { +) -> errors::CustomResult< + ( + api::PaymentMethodResponse, + Option<payment_methods::DataDuplicationCheck>, + ), + errors::VaultError, +> { let payload = payment_methods::StoreLockerReq::LockerCard(payment_methods::StoreCardReq { merchant_id: &merchant_account.merchant_id, merchant_customer_id: customer_id.to_owned(), @@ -565,11 +732,7 @@ pub async fn add_card_hs( req, &merchant_account.merchant_id, ); - - Ok(( - payment_method_resp, - store_card_payload.duplicate.unwrap_or(false), - )) + Ok((payment_method_resp, store_card_payload.duplication_check)) } #[instrument(skip_all)] @@ -875,7 +1038,7 @@ pub async fn mock_call_to_locker_hs<'a>( .change_context(errors::VaultError::SaveCardFailed)?; let payload = payment_methods::StoreCardRespPayload { card_reference: response.card_id, - duplicate: Some(false), + duplication_check: None, }; Ok(payment_methods::StoreCardResp { status: "SUCCESS".to_string(), diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 360efb7ddad..59b02d01933 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -62,7 +62,14 @@ pub struct StoreCardResp { #[derive(Debug, Deserialize, Serialize)] pub struct StoreCardRespPayload { pub card_reference: String, - pub duplicate: Option<bool>, + pub duplication_check: Option<DataDuplicationCheck>, +} + +#[derive(Debug, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum DataDuplicationCheck { + Duplicated, + MetaDataChanged, } #[derive(Debug, Deserialize, Serialize)] diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 1b9f512d842..9691ea962fa 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1,3 +1,4 @@ +use api_models::payment_methods::PaymentMethodsData; use common_utils::{ext_traits::ValueExt, pii}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; @@ -6,7 +7,7 @@ use router_env::{instrument, tracing}; use super::helpers; use crate::{ core::{ - errors::{self, ConnectorErrorExt, RouterResult}, + errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt}, mandate, payment_methods, payments, }, logger, @@ -16,7 +17,7 @@ use crate::{ self, api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, domain, - storage::enums as storage_enums, + storage::{self, enums as storage_enums}, }, utils::OptionExt, }; @@ -99,7 +100,7 @@ where .await? }; - let is_duplicate = locker_response.1; + let duplication_check = locker_response.1; let pm_card_details = locker_response.0.card.as_ref().map(|card| { api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from( @@ -114,29 +115,31 @@ where ) .await; - if is_duplicate { - let existing_pm = db - .find_payment_method(&locker_response.0.payment_method_id) - .await; - match existing_pm { - Ok(pm) => { - let pm_metadata = create_payment_method_metadata( - pm.metadata.as_ref(), - connector_token, - )?; - if let Some(metadata) = pm_metadata { - payment_methods::cards::update_payment_method(db, pm, metadata) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to add payment method in db")?; - }; - } - Err(error) => { - match error.current_context() { - errors::StorageError::DatabaseError(err) => match err - .current_context() - { - diesel_models::errors::DatabaseError::NotFound => { + match duplication_check { + Some(duplication_check) => match duplication_check { + payment_methods::transformers::DataDuplicationCheck::Duplicated => { + let existing_pm = db + .find_payment_method(&locker_response.0.payment_method_id) + .await; + match existing_pm { + Ok(pm) => { + let pm_metadata = create_payment_method_metadata( + pm.metadata.as_ref(), + connector_token, + )?; + if let Some(metadata) = pm_metadata { + payment_methods::cards::update_payment_method( + db, pm, metadata, + ) + .await + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable("Failed to add payment method in db")?; + }; + } + Err(err) => { + if err.current_context().is_db_not_found() { let pm_metadata = create_payment_method_metadata(None, connector_token)?; payment_methods::cards::create_payment_method( @@ -150,33 +153,149 @@ where key_store, ) .await - } - _ => { - Err(report!(errors::ApiErrorResponse::InternalServerError) + } else { + Err(err) + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable("Error while finding payment method") + }?; + } + }; + } + payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => { + if let Some(card) = payment_method_create_request.card.clone() { + payment_methods::cards::delete_card_from_locker( + state, + &customer.customer_id, + merchant_id, + &locker_response.0.payment_method_id, + ) + .await?; + + let add_card_resp = payment_methods::cards::add_card_hs( + state, + payment_method_create_request.clone(), + &card, + customer.customer_id.clone(), + merchant_account, + api::enums::LockerChoice::Tartarus, + Some(&locker_response.0.payment_method_id), + ) + .await; + + if let Err(err) = add_card_resp { + logger::error!(vault_err=?err); + db.delete_payment_method_by_merchant_id_payment_method_id( + merchant_id, + &locker_response.0.payment_method_id, + ) + .await + .to_not_found_response( + errors::ApiErrorResponse::PaymentMethodNotFound, + )?; + + Err(report!(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Failed while updating card metadata changes", + ))? + }; + + let existing_pm = db + .find_payment_method(&locker_response.0.payment_method_id) + .await; + match existing_pm { + Ok(pm) => { + let updated_card = Some(CardDetailFromLocker { + scheme: None, + last4_digits: Some( + card.card_number.to_string().split_off( + card.card_number.to_string().len() - 4, + ), + ), + issuer_country: None, + card_number: Some(card.card_number), + expiry_month: Some(card.card_exp_month), + expiry_year: Some(card.card_exp_year), + card_token: None, + card_fingerprint: None, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_network: None, + card_isin: None, + card_issuer: None, + card_type: None, + saved_to_locker: true, + }); + + let updated_pmd = updated_card.as_ref().map(|card| { + PaymentMethodsData::Card( + CardDetailsPaymentMethod::from(card.clone()), + ) + }); + let pm_data_encrypted = + payment_methods::cards::create_encrypted_payment_method_data( + key_store, + updated_pmd, + ) + .await; + + let pm_update = + storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: pm_data_encrypted, + }; + + db.update_payment_method(pm, pm_update) + .await + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) .attach_printable( - "Database Error while finding payment method", - )) + "Failed to add payment method in db", + )?; + } + Err(err) => { + if err.current_context().is_db_not_found() { + payment_methods::cards::insert_payment_method( + db, + &locker_response.0, + payment_method_create_request, + key_store, + merchant_id, + &customer.customer_id, + None, + ) + .await + } else { + Err(err) + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable( + "Error while finding payment method", + ) + }?; } - }, - _ => Err(report!(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Error while finding payment method")), - }?; + } + } } - }; - } else { - let pm_metadata = create_payment_method_metadata(None, connector_token)?; - payment_methods::cards::create_payment_method( - db, - &payment_method_create_request, - &customer.customer_id, - &locker_response.0.payment_method_id, - merchant_id, - pm_metadata, - pm_data_encrypted, - key_store, - ) - .await?; - }; + }, + None => { + let pm_metadata = create_payment_method_metadata(None, connector_token)?; + payment_methods::cards::create_payment_method( + db, + &payment_method_create_request, + &customer.customer_id, + &locker_response.0.payment_method_id, + merchant_id, + pm_metadata, + pm_data_encrypted, + key_store, + ) + .await?; + } + } + Some(locker_response.0.payment_method_id) } else { None @@ -190,7 +309,10 @@ where async fn skip_saving_card_in_locker( merchant_account: &domain::MerchantAccount, payment_method_request: api::PaymentMethodCreate, -) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { +) -> RouterResult<( + api_models::payment_methods::PaymentMethodResponse, + Option<payment_methods::transformers::DataDuplicationCheck>, +)> { let merchant_id = &merchant_account.merchant_id; let customer_id = payment_method_request .clone() @@ -243,7 +365,7 @@ async fn skip_saving_card_in_locker( bank_transfer: None, }; - Ok((pm_resp, false)) + Ok((pm_resp, None)) } None => { let pm_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm"); @@ -261,7 +383,7 @@ async fn skip_saving_card_in_locker( payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), bank_transfer: None, }; - Ok((payment_method_response, false)) + Ok((payment_method_response, None)) } } } @@ -270,7 +392,10 @@ pub async fn save_in_locker( state: &AppState, merchant_account: &domain::MerchantAccount, payment_method_request: api::PaymentMethodCreate, -) -> RouterResult<(api_models::payment_methods::PaymentMethodResponse, bool)> { +) -> RouterResult<( + api_models::payment_methods::PaymentMethodResponse, + Option<payment_methods::transformers::DataDuplicationCheck>, +)> { payment_method_request.validate()?; let merchant_id = &merchant_account.merchant_id; let customer_id = payment_method_request @@ -304,7 +429,7 @@ pub async fn save_in_locker( installment_payment_enabled: false, //[#219] payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219] }; - Ok((payment_method_response, false)) + Ok((payment_method_response, None)) } } }
2023-12-15T14:56:35Z
## Description <!-- Describe your changes in detail --> Currently card duplication and card metadata (card_holder_name, expiry year, expiry month, etc) changes are not being handled in Hyperswitch. Rust locker has the following changes made - a new field `duplication_check` has been added in stored card response. This field can have three values (duplicated, meta_data_changed and null). * `duplicated` : indicates that the entire card details in the card request is already present in the locker. * `meta_data_changed` : indicates that there is already a saved card with same card number but with different card details (like expiry or card holder name). * `null` : indicates that card is not present in the locker. This PR handles above response from locker in two different flows. * During `/payments` api call with `setup_future_usage = on_session` * During `/payment_methods` api call to add card directly Below are the ways in which Hyperswitch will behave based on above 3 values of `duplication_check` * `duplicated` : Since card already exist on locker, just ensure corresponding payment method entry is present in `payment_methods` table. If not we create it with the `payment_method_id` (locker_id) returned by locker. * `meta_data_changed` : Send a delete request to locker. Send a add card request to locker with the updated card details but same `payment_method_id` (This ensures that we don't re-create payment method entry on Hyperswitch side). Next update the `payment_method_data` field in `payment_methods` table to contain the new card details. * `null` : New payment method entry is created as this is a new card. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> # ## i) Directly adding card using `/payment_methods` api - 1. Create a `Customer` ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2csdyoNPcAqi4zqAg0oPDbCjQu4zoMzZ1JOrMDQ9zoe0CZ7rfrdI2r9Ju3o1M7ya' \ --data-raw '{ "email": "guest@example.com", "name": "David", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 2. Hit add card request with the `customer_id` from above request (Try some new test card which shouldn't exist in locker) ``` curl --location 'http://localhost:8080/payment_methods' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2csdyoNPcAqi4zqAg0oPDbCjQu4zoMzZ1JOrMDQ9zoe0CZ7rfrdI2r9Ju3o1M7ya' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "Visa", "card": { "card_number": "4000002500001001", "card_exp_month": "01", "card_exp_year": "42", "card_holder_name": "Devid" }, "customer_id": "{{customer_id}}", "metadata": { "city": "NY", "unit": "245" } }' ``` Below is the locker response I logged for testing purpose - ``` StoreCardRespPayload { card_reference: "3e9223a0-6508-4957-b947-9b2b6f7189b0", duplication_check: None } ``` `duplication_check` says None. Also make sure payment method entry is created in hyperswitch side in using `list_customer_payment_method` api 3. Now try to hit the same add card request without any change in card params. Locker response - ``` StoreCardRespPayload { card_reference: "3e9223a0-6508-4957-b947-9b2b6f7189b0", duplication_check: Some(Duplicated) } ``` `duplication_check` says `Duplicated` which means whole card is found in locker without any change in card metadata (expiry year, expiry month, card holder name, etc) Make sure no new entry is created in `payment_methods` table as this was a duplicate card. Check this by again doing `list_customer_payment_method` and this should still have 1 card. 4. Now change the metadata of card (ex - card holder name) and make add card request. Locker response - ``` StoreCardRespPayload { card_reference: "3e9223a0-6508-4957-b947-9b2b6f7189b0", duplication_check: Some(MetaDataChanged) } ``` `duplication_check` says `MetaDataChanged` which means card was found but some of its metadata was changed. At this point the card details (metadata) must be updated as per request sent. Do `list_customer_payment_method` and this response should have the metadata changes you have done. ## ii) Using `/payments` api with `setup_future_usage = on_session` 1. Create a `Customer` ``` curl --location 'http://localhost:8080/customers' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2csdyoNPcAqi4zqAg0oPDbCjQu4zoMzZ1JOrMDQ9zoe0CZ7rfrdI2r9Ju3o1M7ya' \ --data-raw '{ "email": "guest@example.com", "name": "David", "phone": "999999999", "phone_country_code": "+65", "description": "First customer", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 2. Hit `/payments` api with `setup_future_usage = on_session` with card thats not present in locker. Make sure to use above `customer_id` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2csdyoNPcAqi4zqAg0oPDbCjQu4zoMzZ1JOrMDQ9zoe0CZ7rfrdI2r9Ju3o1M7ya' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "{{customer_id}}", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "setup_future_usage": "on_session", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4000002500001001", "card_exp_month": "12", "card_exp_year": "42", "card_holder_name": "David", "card_cvc": "900" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "business_label": "default", "business_country": "US" }' ``` This time card has to be saved in locker and `payment_methods` entry has to be created in hyperswitch. Verify by hitting `list_customer_payment_method`. 3. Now for the same customer try to make another payment without changing anything (same card). This time as this is a duplicate card, no new entry has to be created in `payment_methods` table. Verify by hitting `list_customer_payment_method` and this should still have 1 card. 4. Change some metadata and make a payment for same customer. 5. Do `list_customer_payment_method` and this response should have the metadata changes you have done.
3a869a2d5731a2393a687ed7773eda5344bd8e3f
Create a merchant account, api key and stripe mca. This PR has to be tested in below 2 flows as these are the two ways in which we can send add card request to locker. i) Directly adding card using `/payment_methods` api ii) Using `/payments` api with `setup_future_usage = on_session`
[ "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/payment_methods/transformers.rs", "crates/router/src/core/payments/tokenization.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3099
Bug: [FEATURE] Make PM auth service generic across Payment Method types ### Feature Description Currently, PM auth only supports ACH, need to make it generic across SEPA, BACS as well. ### Possible Implementation Will probably need some kind of parent structure to differentiate between types ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 35193b958f2..9873f62bfe1 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -222,17 +222,24 @@ pub struct PaymentMethodDataBankCreds { pub connector_details: Vec<BankAccountConnectorDetails>, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct BankAccountTokenData { + pub payment_method_type: api_enums::PaymentMethodType, + pub payment_method: api_enums::PaymentMethod, + pub connector_details: BankAccountConnectorDetails, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct BankAccountConnectorDetails { pub connector: String, - pub account_id: String, + pub account_id: masking::Secret<String>, pub mca_id: String, pub access_token: BankAccountAccessCreds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub enum BankAccountAccessCreds { - AccessToken(String), + AccessToken(masking::Secret<String>), } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs index 5e1ad67aead..f163875958e 100644 --- a/crates/pm_auth/src/connector/plaid/transformers.rs +++ b/crates/pm_auth/src/connector/plaid/transformers.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; -use common_enums::PaymentMethodType; -use masking::Secret; +use common_enums::{PaymentMethod, PaymentMethodType}; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{core::errors, types}; @@ -200,13 +200,19 @@ pub struct PlaidBankAccountCredentialsBacs { impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> { + let options = item.request.optional_ids.as_ref().map(|bank_account_ids| { + let ids = bank_account_ids + .ids + .iter() + .map(|id| id.peek().to_string()) + .collect::<Vec<_>>(); + + BankAccountCredentialsOptions { account_ids: ids } + }); + Ok(Self { - access_token: item.request.access_token.clone(), - options: item.request.optional_ids.as_ref().map(|bank_account_ids| { - BankAccountCredentialsOptions { - account_ids: bank_account_ids.ids.clone(), - } - }), + access_token: item.request.access_token.peek().to_string(), + options, }) } } @@ -232,26 +238,84 @@ impl<F, T> ) -> Result<Self, Self::Error> { let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts); let mut bank_account_vec = Vec::new(); - let mut id_to_suptype = HashMap::new(); + let mut id_to_subtype = HashMap::new(); accounts_info.into_iter().for_each(|acc| { - id_to_suptype.insert(acc.account_id, (acc.subtype, acc.name)); + id_to_subtype.insert(acc.account_id, (acc.subtype, acc.name)); }); account_numbers.ach.into_iter().for_each(|ach| { let (acc_type, acc_name) = - if let Some((_type, name)) = id_to_suptype.get(&ach.account_id) { + if let Some((_type, name)) = id_to_subtype.get(&ach.account_id) { (_type.to_owned(), Some(name.clone())) } else { (None, None) }; + let account_details = + types::PaymentMethodTypeDetails::Ach(types::BankAccountDetailsAch { + account_number: Secret::new(ach.account), + routing_number: Secret::new(ach.routing), + }); + let bank_details_new = types::BankAccountDetails { account_name: acc_name, - account_number: ach.account, - routing_number: ach.routing, + account_details, payment_method_type: PaymentMethodType::Ach, - account_id: ach.account_id, + payment_method: PaymentMethod::BankDebit, + account_id: ach.account_id.into(), + account_type: acc_type, + }; + + bank_account_vec.push(bank_details_new); + }); + + account_numbers.bacs.into_iter().for_each(|bacs| { + let (acc_type, acc_name) = + if let Some((_type, name)) = id_to_subtype.get(&bacs.account_id) { + (_type.to_owned(), Some(name.clone())) + } else { + (None, None) + }; + + let account_details = + types::PaymentMethodTypeDetails::Bacs(types::BankAccountDetailsBacs { + account_number: Secret::new(bacs.account), + sort_code: Secret::new(bacs.sort_code), + }); + + let bank_details_new = types::BankAccountDetails { + account_name: acc_name, + account_details, + payment_method_type: PaymentMethodType::Bacs, + payment_method: PaymentMethod::BankDebit, + account_id: bacs.account_id.into(), + account_type: acc_type, + }; + + bank_account_vec.push(bank_details_new); + }); + + account_numbers.international.into_iter().for_each(|sepa| { + let (acc_type, acc_name) = + if let Some((_type, name)) = id_to_subtype.get(&sepa.account_id) { + (_type.to_owned(), Some(name.clone())) + } else { + (None, None) + }; + + let account_details = + types::PaymentMethodTypeDetails::Sepa(types::BankAccountDetailsSepa { + iban: Secret::new(sepa.iban), + bic: Secret::new(sepa.bic), + }); + + let bank_details_new = types::BankAccountDetails { + account_name: acc_name, + account_details, + payment_method_type: PaymentMethodType::Sepa, + payment_method: PaymentMethod::BankDebit, + account_id: sepa.account_id.into(), account_type: acc_type, }; diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs index 6f5875247f1..51fd796072b 100644 --- a/crates/pm_auth/src/types.rs +++ b/crates/pm_auth/src/types.rs @@ -3,7 +3,7 @@ pub mod api; use std::marker::PhantomData; use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}; -use common_enums::PaymentMethodType; +use common_enums::{PaymentMethod, PaymentMethodType}; use masking::Secret; #[derive(Debug, Clone)] pub struct PaymentAuthRouterData<F, Request, Response> { @@ -55,13 +55,13 @@ pub type ExchangeTokenRouterData = #[derive(Debug, Clone)] pub struct BankAccountCredentialsRequest { - pub access_token: String, + pub access_token: Secret<String>, pub optional_ids: Option<BankAccountOptionalIDs>, } #[derive(Debug, Clone)] pub struct BankAccountOptionalIDs { - pub ids: Vec<String>, + pub ids: Vec<Secret<String>>, } #[derive(Debug, Clone)] @@ -72,13 +72,37 @@ pub struct BankAccountCredentialsResponse { #[derive(Debug, Clone)] pub struct BankAccountDetails { pub account_name: Option<String>, - pub account_number: String, - pub routing_number: String, + pub account_details: PaymentMethodTypeDetails, pub payment_method_type: PaymentMethodType, - pub account_id: String, + pub payment_method: PaymentMethod, + pub account_id: Secret<String>, pub account_type: Option<String>, } +#[derive(Debug, Clone)] +pub enum PaymentMethodTypeDetails { + Ach(BankAccountDetailsAch), + Bacs(BankAccountDetailsBacs), + Sepa(BankAccountDetailsSepa), +} +#[derive(Debug, Clone)] +pub struct BankAccountDetailsAch { + pub account_number: Secret<String>, + pub routing_number: Secret<String>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountDetailsBacs { + pub account_number: Secret<String>, + pub sort_code: Secret<String>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountDetailsSepa { + pub iban: Secret<String>, + pub bic: Secret<String>, +} + pub type BankDetailsRouterData = PaymentAuthRouterData< BankAccountCredentials, BankAccountCredentialsRequest, diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index f9d98647d1b..7ade016856c 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -6453,7 +6453,15 @@ impl Default for super::settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::new(), + common: HashMap::from([ ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + )]), })] )} ), @@ -6466,7 +6474,15 @@ impl Default for super::settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::new(), + common: HashMap::from([ ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + )]), } ), ]), @@ -6481,7 +6497,15 @@ impl Default for super::settings::RequiredFields { RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), - common: HashMap::new(), + common: HashMap::from([ ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_first_name".to_string(), + field_type: enums::FieldType::UserBillingName, + value: None, + } + )]), } ), ]), diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 60abf0701a5..41efea14942 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -7,7 +7,7 @@ use api_models::{ admin::{self, PaymentMethodsEnabled}, enums::{self as api_enums}, payment_methods::{ - BankAccountConnectorDetails, CardDetailsPaymentMethod, CardNetworkTypes, + BankAccountTokenData, CardDetailsPaymentMethod, CardNetworkTypes, CustomerDefaultPaymentMethodResponse, MaskedBankDetails, PaymentExperienceTypes, PaymentMethodsData, RequestPaymentMethodTypes, RequiredFieldInfo, ResponsePaymentMethodIntermediate, ResponsePaymentMethodTypes, @@ -2824,14 +2824,14 @@ pub async fn list_customer_payment_method( enums::PaymentMethod::BankDebit => { // Retrieve the pm_auth connector details so that it can be tokenized - let bank_account_connector_details = get_bank_account_connector_details(&pm, key) + let bank_account_token_data = get_bank_account_connector_details(&pm, key) .await .unwrap_or_else(|err| { logger::error!(error=?err); None }); - if let Some(connector_details) = bank_account_connector_details { - let token_data = PaymentTokenData::AuthBankDebit(connector_details); + if let Some(data) = bank_account_token_data { + let token_data = PaymentTokenData::AuthBankDebit(data); (None, None, token_data) } else { continue; @@ -3133,7 +3133,7 @@ async fn get_masked_bank_details( async fn get_bank_account_connector_details( pm: &payment_method::PaymentMethod, key: &[u8], -) -> errors::RouterResult<Option<BankAccountConnectorDetails>> { +) -> errors::RouterResult<Option<BankAccountTokenData>> { let payment_method_data = decrypt::<serde_json::Value, masking::WithType>(pm.payment_method_data.clone(), key) .await @@ -3162,12 +3162,19 @@ async fn get_bank_account_connector_details( .connector_details .first() .ok_or(errors::ApiErrorResponse::InternalServerError)?; - Ok(Some(BankAccountConnectorDetails { - connector: connector_details.connector.clone(), - account_id: connector_details.account_id.clone(), - mca_id: connector_details.mca_id.clone(), - access_token: connector_details.access_token.clone(), - })) + + let pm_type = pm + .payment_method_type + .get_required_value("payment_method_type") + .attach_printable("PaymentMethodType not found")?; + + let token_data = BankAccountTokenData { + payment_method_type: pm_type, + payment_method: pm.payment_method, + connector_details: connector_details.clone(), + }; + + Ok(Some(token_data)) } }, None => Ok(None), diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index 21ba27eac17..20db03a26a6 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -5,6 +5,7 @@ use api_models::{ payment_methods::{self, BankAccountAccessCreds}, payments::{AddressDetails, BankDebitBilling, BankDebitData, PaymentMethodData}, }; +use common_enums::PaymentMethodType; use hex; pub mod helpers; pub mod transformers; @@ -18,7 +19,7 @@ use common_utils::{ use data_models::payments::PaymentIntent; use error_stack::{IntoReport, ResultExt}; use helpers::PaymentAuthConnectorDataExt; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::{ connector::plaid::transformers::PlaidAuthType, types::{ @@ -273,7 +274,7 @@ async fn store_bank_details_in_payment_methods( merchant_account: domain::MerchantAccount, state: AppState, bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse, - connector_details: (&str, String), + connector_details: (&str, Secret<String>), mca_id: String, ) -> RouterResult<()> { let key = key_store.key.get_inner().peek(); @@ -357,7 +358,31 @@ async fn store_bank_details_in_payment_methods( let mut new_entries: Vec<storage::PaymentMethodNew> = Vec::new(); for creds in bank_account_details_resp.credentials { - let hash_string = format!("{}-{}", creds.account_number, creds.routing_number); + let (account_number, hash_string) = match creds.account_details { + pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => ( + ach.account_number.clone(), + format!( + "{}-{}-{}", + ach.account_number.peek(), + ach.routing_number.peek(), + PaymentMethodType::Ach, + ), + ), + pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => ( + bacs.account_number.clone(), + format!( + "{}-{}-{}", + bacs.account_number.peek(), + bacs.sort_code.peek(), + PaymentMethodType::Bacs + ), + ), + pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => ( + sepa.iban.clone(), + format!("{}-{}", sepa.iban.expose(), PaymentMethodType::Sepa), + ), + }; + let generated_hash = hex::encode( HmacSha256::sign_message(&HmacSha256, pm_auth_key.as_bytes(), hash_string.as_bytes()) .change_context(ApiErrorResponse::InternalServerError) @@ -366,8 +391,8 @@ async fn store_bank_details_in_payment_methods( let contains_account = hash_to_payment_method.get(&generated_hash); let mut pmd = payment_methods::PaymentMethodDataBankCreds { - mask: creds - .account_number + mask: account_number + .peek() .chars() .rev() .take(4) @@ -472,10 +497,10 @@ pub async fn get_bank_account_creds( connector: PaymentAuthConnectorData, merchant_account: &domain::MerchantAccount, connector_name: &str, - access_token: &str, + access_token: &Secret<String>, auth_type: pm_auth_types::ConnectorAuthType, state: &AppState, - bank_account_id: Option<String>, + bank_account_id: Option<Secret<String>>, ) -> RouterResult<pm_auth_types::BankAccountCredentialsResponse> { let connector_integration_bank_details: BoxedConnectorIntegration< '_, @@ -489,7 +514,7 @@ pub async fn get_bank_account_creds( merchant_id: Some(merchant_account.merchant_id.clone()), connector: Some(connector_name.to_string()), request: pm_auth_types::BankAccountCredentialsRequest { - access_token: access_token.to_string(), + access_token: access_token.clone(), optional_ids: bank_account_id .map(|id| pm_auth_types::BankAccountOptionalIDs { ids: vec![id] }), }, @@ -530,7 +555,7 @@ async fn get_access_token_from_exchange_api( payload: &api_models::pm_auth::ExchangeTokenCreateRequest, auth_type: &pm_auth_types::ConnectorAuthType, state: &AppState, -) -> RouterResult<String> { +) -> RouterResult<Secret<String>> { let connector_integration: BoxedConnectorIntegration< '_, ExchangeToken, @@ -573,7 +598,7 @@ async fn get_access_token_from_exchange_api( })?; let access_token = exchange_token_resp.access_token; - Ok(access_token) + Ok(Secret::new(access_token)) } async fn get_selected_config_from_redis( @@ -593,7 +618,9 @@ async fn get_selected_config_from_redis( "Vec<PaymentMethodAuthConnectorChoice>", ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "payment method auth connector name not found".to_string(), + }) .attach_printable("Failed to get payment method auth choices from redis")?; let selected_config = pm_auth_configs @@ -603,7 +630,7 @@ async fn get_selected_config_from_redis( && conf.payment_method_type == payload.payment_method_type }) .ok_or(ApiErrorResponse::GenericNotFoundError { - message: "connector name not found".to_string(), + message: "payment method auth connector name not found".to_string(), }) .into_report()? .clone(); @@ -614,14 +641,14 @@ async fn get_selected_config_from_redis( pub async fn retrieve_payment_method_from_auth_service( state: &AppState, key_store: &domain::MerchantKeyStore, - auth_token: &payment_methods::BankAccountConnectorDetails, + auth_token: &payment_methods::BankAccountTokenData, payment_intent: &PaymentIntent, customer: &Option<domain::Customer>, ) -> RouterResult<Option<(PaymentMethodData, enums::PaymentMethod)>> { let db = state.store.as_ref(); let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( - auth_token.connector.as_str(), + auth_token.connector_details.connector.as_str(), )?; let merchant_account = db @@ -632,12 +659,12 @@ pub async fn retrieve_payment_method_from_auth_service( let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( &payment_intent.merchant_id, - &auth_token.mca_id, + &auth_token.connector_details.mca_id, key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { - id: auth_token.mca_id.clone(), + id: auth_token.connector_details.mca_id.clone(), }) .attach_printable( "error while fetching merchant_connector_account from merchant_id and connector name", @@ -645,24 +672,27 @@ pub async fn retrieve_payment_method_from_auth_service( let auth_type = pm_auth_helpers::get_connector_auth_type(mca)?; - let BankAccountAccessCreds::AccessToken(access_token) = &auth_token.access_token; + let BankAccountAccessCreds::AccessToken(access_token) = + &auth_token.connector_details.access_token; let bank_account_creds = get_bank_account_creds( connector, &merchant_account, - &auth_token.connector, + &auth_token.connector_details.connector, access_token, auth_type, state, - Some(auth_token.account_id.clone()), + Some(auth_token.connector_details.account_id.clone()), ) .await?; - logger::debug!("bank_creds: {:?}", bank_account_creds); - let bank_account = bank_account_creds .credentials - .first() + .iter() + .find(|acc| { + acc.payment_method_type == auth_token.payment_method_type + && acc.payment_method == auth_token.payment_method + }) .ok_or(errors::ApiErrorResponse::InternalServerError) .into_report() .attach_printable("Bank account details not found")?; @@ -686,7 +716,12 @@ pub async fn retrieve_payment_method_from_auth_service( let name = address .as_ref() - .and_then(|addr| addr.first_name.clone().map(|name| name.into_inner())); + .and_then(|addr| addr.first_name.clone().map(|name| name.into_inner())) + .ok_or(errors::ApiErrorResponse::GenericNotFoundError { + message: "billing_first_name not found".to_string(), + }) + .into_report() + .attach_printable("billing_first_name not found")?; let address_details = address.clone().map(|addr| { let line1 = addr.line1.map(|line1| line1.into_inner()); @@ -716,20 +751,41 @@ pub async fn retrieve_payment_method_from_auth_service( .map(common_utils::pii::Email::from) .get_required_value("email")?; - let payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { - billing_details: BankDebitBilling { - name: name.unwrap_or_default(), - email, - address: address_details, - }, - account_number: masking::Secret::new(bank_account.account_number.clone()), - routing_number: masking::Secret::new(bank_account.routing_number.clone()), - card_holder_name: None, - bank_account_holder_name: None, - bank_name: None, - bank_type, - bank_holder_type: None, - }); + let billing_details = BankDebitBilling { + name, + email, + address: address_details, + }; + + let payment_method_data = match &bank_account.account_details { + pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => { + PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { + billing_details, + account_number: ach.account_number.clone(), + routing_number: ach.routing_number.clone(), + card_holder_name: None, + bank_account_holder_name: None, + bank_name: None, + bank_type, + bank_holder_type: None, + }) + } + pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => { + PaymentMethodData::BankDebit(BankDebitData::BacsBankDebit { + billing_details, + account_number: bacs.account_number.clone(), + sort_code: bacs.sort_code.clone(), + bank_account_holder_name: None, + }) + } + pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => { + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { + billing_details, + iban: sepa.iban.clone(), + bank_account_holder_name: None, + }) + } + }; Ok(Some((payment_method_data, enums::PaymentMethod::BankDebit))) } diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index d3339b7c4be..e1d74c70089 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -52,7 +52,7 @@ pub enum PaymentTokenData { TemporaryGeneric(GenericTokenData), Permanent(CardTokenData), PermanentCard(CardTokenData), - AuthBankDebit(payment_methods::BankAccountConnectorDetails), + AuthBankDebit(payment_methods::BankAccountTokenData), WalletToken(WalletTokenData), }
2023-12-12T10:21:17Z
## Description <!-- Describe your changes in detail --> Support for SEPA and BACS in direct debit PM auth. Earlier we only supported ACH based response from pm auth connector in PM auth, now have added support for BACS and SEPA based responses as well. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
1e32c6e873711e4f7715176c7d1057c18d4ec540
Have tested locally by hardcoding response from connector. This cannot be tested as it is in sandbox because Plaid always sends a basic ACH based response in sandbox which won't trigger the response structure for BACS and SEPA (the implementation of this PR). A simple sanity testing however can be done for the feature, refer to this for testing instructions - https://github.com/juspay/hyperswitch/pull/3047 <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/2ec82cb1-8a1e-4d6f-b4ad-913bc082db54"> <img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/aafcaa7a-fdca-4344-9ed1-8d3e19b91006">
[ "crates/api_models/src/payment_methods.rs", "crates/pm_auth/src/connector/plaid/transformers.rs", "crates/pm_auth/src/types.rs", "crates/router/src/configs/defaults.rs", "crates/router/src/core/payment_methods/cards.rs", "crates/router/src/core/pm_auth.rs", "crates/router/src/types/storage/payment_metho...
juspay/hyperswitch
juspay__hyperswitch-3440
Bug: [FEATURE] Add `KMS` encrypt utility ### Feature Description Introducing a new functionality, that seamlessly integrates with Key Management Service (KMS), offering a robust encryption solution. This feature empowers users to encrypt any value with ease, ensuring enhanced security and data protection. Leveraging KMS, the function provides a reliable and scalable approach to safeguard sensitive information, making it a valuable addition for bolstering the overall security posture of our application. ### Testing <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test cases written for encrpyt as well as decrypt functions. <img width="1400" alt="Screenshot 2023-12-12 at 13 33 03" src="https://github.com/juspay/hyperswitch/assets/61520228/638b199f-15ac-473e-84f5-55c3d8353715">
diff --git a/crates/external_services/src/kms.rs b/crates/external_services/src/kms.rs index 31c82253fe8..04a58e4b23f 100644 --- a/crates/external_services/src/kms.rs +++ b/crates/external_services/src/kms.rs @@ -75,7 +75,7 @@ impl KmsClient { // Logging using `Debug` representation of the error as the `Display` // representation does not hold sufficient information. logger::error!(kms_sdk_error=?error, "Failed to KMS decrypt data"); - metrics::AWS_KMS_FAILURES.add(&metrics::CONTEXT, 1, &[]); + metrics::AWS_KMS_DECRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); error }) .into_report() @@ -96,11 +96,51 @@ impl KmsClient { Ok(output) } + + /// Encrypts the provided String data using the AWS KMS SDK. We assume that + /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and + /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in + /// a machine that is able to assume an IAM role. + pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, KmsError> { + let start = Instant::now(); + let plaintext_blob = Blob::new(data.as_ref()); + + let encrypted_output = self + .inner_client + .encrypt() + .key_id(&self.key_id) + .plaintext(plaintext_blob) + .send() + .await + .map_err(|error| { + // Logging using `Debug` representation of the error as the `Display` + // representation does not hold sufficient information. + logger::error!(kms_sdk_error=?error, "Failed to KMS encrypt data"); + metrics::AWS_KMS_ENCRYPTION_FAILURES.add(&metrics::CONTEXT, 1, &[]); + error + }) + .into_report() + .change_context(KmsError::EncryptionFailed)?; + + let output = encrypted_output + .ciphertext_blob + .ok_or(KmsError::MissingCiphertextEncryptionOutput) + .into_report() + .map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?; + let time_taken = start.elapsed(); + metrics::AWS_KMS_ENCRYPT_TIME.record(&metrics::CONTEXT, time_taken.as_secs_f64(), &[]); + + Ok(output) + } } /// Errors that could occur during KMS operations. #[derive(Debug, thiserror::Error)] pub enum KmsError { + /// An error occurred when base64 encoding input data. + #[error("Failed to base64 encode input data")] + Base64EncodingFailed, + /// An error occurred when base64 decoding input data. #[error("Failed to base64 decode input data")] Base64DecodingFailed, @@ -109,10 +149,18 @@ pub enum KmsError { #[error("Failed to KMS decrypt input data")] DecryptionFailed, + /// An error occurred when KMS encrypting input data. + #[error("Failed to KMS encrypt input data")] + EncryptionFailed, + /// The KMS decrypted output does not include a plaintext output. #[error("Missing plaintext KMS decryption output")] MissingPlaintextDecryptionOutput, + /// The KMS encrypted output does not include a ciphertext output. + #[error("Missing ciphertext KMS encryption output")] + MissingCiphertextEncryptionOutput, + /// An error occurred UTF-8 decoding KMS decrypted output. #[error("Failed to UTF-8 decode decryption output")] Utf8DecodingFailed, @@ -147,3 +195,50 @@ impl common_utils::ext_traits::ConfigExt for KmsValue { self.0.peek().is_empty_after_trim() } } + +#[cfg(test)] +mod tests { + #![allow(clippy::expect_used)] + #[tokio::test] + async fn check_kms_encryption() { + std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); + std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); + use super::*; + let config = KmsConfig { + key_id: "YOUR KMS KEY ID".to_string(), + region: "AWS REGION".to_string(), + }; + + let data = "hello".to_string(); + let binding = data.as_bytes(); + let kms_encrypted_fingerprint = KmsClient::new(&config) + .await + .encrypt(binding) + .await + .expect("kms encryption failed"); + + println!("{}", kms_encrypted_fingerprint); + } + + #[tokio::test] + async fn check_kms_decrypt() { + std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY"); + std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID"); + use super::*; + let config = KmsConfig { + key_id: "YOUR KMS KEY ID".to_string(), + region: "AWS REGION".to_string(), + }; + + // Should decrypt to hello + let data = "KMS ENCRYPTED CIPHER".to_string(); + let binding = data.as_bytes(); + let kms_encrypted_fingerprint = KmsClient::new(&config) + .await + .decrypt(binding) + .await + .expect("kms decryption failed"); + + println!("{}", kms_encrypted_fingerprint); + } +} diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs index fa57a0bac9c..ccf1db47a3a 100644 --- a/crates/external_services/src/lib.rs +++ b/crates/external_services/src/lib.rs @@ -26,8 +26,12 @@ pub mod metrics { global_meter!(GLOBAL_METER, "EXTERNAL_SERVICES"); #[cfg(feature = "kms")] - counter_metric!(AWS_KMS_FAILURES, GLOBAL_METER); // No. of AWS KMS API failures + counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures + #[cfg(feature = "kms")] + counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures #[cfg(feature = "kms")] histogram_metric!(AWS_KMS_DECRYPT_TIME, GLOBAL_METER); // Histogram for KMS decryption time (in sec) + #[cfg(feature = "kms")] + histogram_metric!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for KMS encryption time (in sec) } diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 192df1a0929..b3629ab7d52 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -6,7 +6,9 @@ global_meter!(GLOBAL_METER, "ROUTER_API"); counter_metric!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses #[cfg(feature = "kms")] -counter_metric!(AWS_KMS_FAILURES, GLOBAL_METER); // No. of AWS KMS API failures +counter_metric!(AWS_KMS_ENCRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Encryption failures +#[cfg(feature = "kms")] +counter_metric!(AWS_KMS_DECRYPTION_FAILURES, GLOBAL_METER); // No. of AWS KMS Decryption failures // API Level Metrics counter_metric!(REQUESTS_RECEIVED, GLOBAL_METER);
2023-12-12T08:15:43Z
## Description <!-- Describe your changes in detail --> #
1add2c059f4fb5653f33e2f3ce454793caf2d595
Test cases written for encrpyt as well as decrypt functions. <img width="1400" alt="Screenshot 2023-12-12 at 13 33 03" src="https://github.com/juspay/hyperswitch/assets/61520228/638b199f-15ac-473e-84f5-55c3d8353715">
[ "crates/external_services/src/kms.rs", "crates/external_services/src/lib.rs", "crates/router/src/routes/metrics.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3106
Bug: [FEATURE] Add missing routing features to default feature list and release feature list for Hyperswitch Router ### Feature Description Add routing features like business profile routing as well as connector choice mca id to the default feature lit as well as the release feature list. ### Possible Implementation Add missing features to the default and release feature lists ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Makefile b/Makefile index 9b62b3c5c99..780d5a993c9 100644 --- a/Makefile +++ b/Makefile @@ -9,6 +9,10 @@ eq = $(if $(or $(1),$(2)),$(and $(findstring $(1),$(2)),\ $(findstring $(2),$(1))),1) + +ROOT_DIR_WITH_SLASH := $(dir $(realpath $(lastword $(MAKEFILE_LIST)))) +ROOT_DIR := $(realpath $(ROOT_DIR_WITH_SLASH)) + # # = Targets # @@ -67,6 +71,14 @@ fmt : clippy : cargo clippy --all-features --all-targets -- -D warnings +# Build the DSL crate as a WebAssembly JS library +# +# Usage : +# make euclid-wasm + +euclid-wasm: + wasm-pack build --target web --out-dir $(ROOT_DIR)/wasm --out-name euclid $(ROOT_DIR)/crates/euclid_wasm -- --features dummy_connector + # Run Rust tests of project. # # Usage : @@ -93,4 +105,4 @@ precommit : fmt clippy test hack: - cargo hack check --workspace --each-feature --all-targets \ No newline at end of file + cargo hack check --workspace --each-feature --all-targets diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index 8c96a7f67da..51288a9d0fe 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -11,6 +11,7 @@ crate-type = ["cdylib"] [features] default = ["connector_choice_bcompat"] +release = ["connector_choice_bcompat", "connector_choice_mca_id"] connector_choice_bcompat = ["api_models/connector_choice_bcompat"] connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connector_choice_mca_id", "kgraph_utils/connector_choice_mca_id"] dummy_connector = ["kgraph_utils/dummy_connector"] diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index b2f7f8b94a9..13324aa59a2 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -9,14 +9,14 @@ readme = "README.md" license.workspace = true [features] -default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "profile_specific_fallback_routing", "retry", "frm"] +default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] s3 = ["dep:aws-sdk-s3", "dep:aws-config"] kms = ["external_services/kms", "dep:aws-config"] email = ["external_services/email", "dep:aws-config", "olap"] frm = [] basilisk = ["kms"] stripe = ["dep:serde_qs"] -release = ["kms", "stripe", "basilisk", "s3", "email", "business_profile_routing", "accounts_cache", "kv_store", "profile_specific_fallback_routing"] +release = ["kms", "stripe", "basilisk", "s3", "email", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"]
2023-12-11T12:11:43Z
## Description <!-- Describe your changes in detail --> This PR adds required routing features to the release feature list for Hyperswitch and also updates the Makefile with a command to build the euclid WASM. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Filling in missing features to be enabled by default. #
151a30f4eed10924cd93bf7f4f66976af0ab8314
Local cargo build
[ "Makefile", "crates/euclid_wasm/Cargo.toml", "crates/router/Cargo.toml" ]
juspay/hyperswitch
juspay__hyperswitch-3466
Bug: [REFACTOR] Make the function to deserialize hashsets more generic when deserializing application configs ### Description As of opening this issue, there are multiple functions to deserialize hashsets with similar logic. These functions can be made generic, and reduced to one common function for deserializing all types. Links to relevant functions: 1. https://github.com/juspay/hyperswitch/blob/0e4e18441d024b7d669b27d6f8a2feb3eccedb2a/crates/router/src/configs/settings.rs#L215-L242 2. https://github.com/juspay/hyperswitch/blob/0e4e18441d024b7d669b27d6f8a2feb3eccedb2a/crates/router/src/configs/settings.rs#L327-L355 3. https://github.com/juspay/hyperswitch/blob/0e4e18441d024b7d669b27d6f8a2feb3eccedb2a/crates/router/src/configs/settings.rs#L419-L469 4. https://github.com/juspay/hyperswitch/blob/0e4e18441d024b7d669b27d6f8a2feb3eccedb2a/crates/router/src/configs/settings.rs#L759-L772 In addition, the existing functions ignore any deserialization errors in case incorrect or unrecognized enum variants are provided, which causes the application to completely ignore those configuration entries. This would also have to be handled, to raise errors in case incorrect values are provided.
diff --git a/Cargo.lock b/Cargo.lock index 5623fd9f729..24fedf82a27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2603,9 +2603,9 @@ dependencies = [ [[package]] name = "fred" -version = "7.0.0" +version = "7.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2e8094c30c33132e948eb7e1b740cfdaa5a6702610bd3a2744002ec3575cd68" +checksum = "9282e65613822eea90c99872c51afa1de61542215cb11f91456a93f50a5a131a" dependencies = [ "arc-swap", "async-trait", @@ -2626,6 +2626,7 @@ dependencies = [ "tracing", "tracing-futures", "url", + "urlencoding", ] [[package]] @@ -5340,16 +5341,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "rust_decimal_macros" -version = "1.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e43721f4ef7060ebc2c3ede757733209564ca8207f47674181bcd425dd76945" -dependencies = [ - "quote", - "rust_decimal", -] - [[package]] name = "rustc-demangle" version = "0.1.23" @@ -5512,11 +5503,9 @@ dependencies = [ [[package]] name = "rusty-money" version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b28f881005eac7ad8d46b6f075da5f322bd7f4f83a38720fc069694ddadd683" +source = "git+https://github.com/varunsrin/rusty_money?rev=bbc0150742a0fff905225ff11ee09388e9babdcc#bbc0150742a0fff905225ff11ee09388e9babdcc" dependencies = [ "rust_decimal", - "rust_decimal_macros", ] [[package]] diff --git a/config/config.example.toml b/config/config.example.toml index 0ad50736e9e..3da1cd0daa0 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -415,7 +415,7 @@ alfamart = { country = "ID", currency = "IDR" } indomaret = { country = "ID", currency = "IDR" } open_banking_uk = { country = "GB", currency = "GBP" } oxxo = { country = "MX", currency = "MXN" } -pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } seven_eleven = { country = "JP", currency = "JPY" } lawson = { country = "JP", currency = "JPY" } mini_stop = { country = "JP", currency = "JPY" } @@ -452,7 +452,7 @@ connector_list = "gocardless,stax,stripe" payout_connector_list = "wise" [bank_config.online_banking_fpx] -adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" [bank_config.online_banking_thailand] adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 4a858588b50..d377b3359c9 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -4,7 +4,7 @@ eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" -online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24" online_banking_slovakia.adyen.banks = "e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo" online_banking_thailand.adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" @@ -133,20 +133,20 @@ giropay = { country = "DE", currency = "EUR" } google_pay.country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" ideal = { country = "NL", currency = "EUR" } klarna = { country = "AT,BE,DK,FI,FR,DE,IE,IT,NL,NO,ES,SE,GB,US,CA", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } -paypal.country = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" +paypal.currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } [pm_filters.adyen] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } alfamart = { country = "ID", currency = "IDR" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } ali_pay_hk = { country = "HK", currency = "HKD" } alma = { country = "FR", currency = "EUR" } -apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,UK,SE,NO,AK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } +apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,GB,SE,NO,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } atome = { country = "MY,SG", currency = "MYR,SGD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } bca_bank_transfer = { country = "ID", currency = "IDR" } bizum = { country = "ES", currency = "EUR" } @@ -162,11 +162,11 @@ family_mart = { country = "JP", currency = "JPY" } gcash = { country = "PH", currency = "PHP" } giropay = { country = "DE", currency = "EUR" } go_pay = { country = "ID", currency = "IDR" } -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -184,20 +184,20 @@ open_banking_uk = { country = "GB", currency = "GBP" } oxxo = { country = "MX", currency = "MXN" } pay_bright = { country = "CA", currency = "CAD" } pay_easy = { country = "JP", currency = "JPY" } -pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } twint = { country = "CH", currency = "CHF" } vipps = { country = "NO", currency = "NOK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD,CNY" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD,CNY" } [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 376ae579a50..d4671d3a99d 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -4,9 +4,9 @@ eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" -online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24" -online_banking_slovakia.adyen.banks = "e_platby_v_u_b,e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo,volksbank_gruppe,volkskredit_bank_ag,vr_bank_braunau" +online_banking_slovakia.adyen.banks = "e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" online_banking_thailand.adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" open_banking_uk.adyen.banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled" przelewy24.stripe.banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank" @@ -127,17 +127,17 @@ payout_eligibility = true [pm_filters.default] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD,CNY" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD,CNY" } apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } blik = { country = "PL", currency = "PLN" } eps = { country = "AT", currency = "EUR" } giropay = { country = "DE", currency = "EUR" } -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } mb_way = { country = "PT", currency = "EUR" } mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } online_banking_czech_republic = { country = "CZ", currency = "EUR,CZK" } @@ -145,24 +145,24 @@ online_banking_finland = { country = "FI", currency = "EUR" } online_banking_poland = { country = "PL", currency = "PLN" } online_banking_slovakia = { country = "SK", currency = "EUR,CZK" } pay_bright = { country = "CA", currency = "CAD" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } [pm_filters.adyen] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,CA,ES,FR,IT,NZ,UK,US", currency = "USD,AUD,CAD,NZD,GBP" } +afterpay_clearpay = { country = "AU,CA,ES,FR,IT,NZ,GB,US", currency = "USD,AUD,CAD,NZD,GBP" } alfamart = { country = "ID", currency = "IDR" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } ali_pay_hk = { country = "HK", currency = "HKD" } alma = { country = "FR", currency = "EUR" } -apple_pay = { country = "AE,AK,AM,AR,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CN,CO,CR,CY,CZ,DE,DK,EE,ES,FI,FO,FR,GB,GE,GG,GL,GR,HK,HR,HU,IE,IL,IM,IS,IT,JE,JO,JP,KW,KZ,LI,LT,LU,LV,MC,MD,ME,MO,MT,MX,MY,NL,NO,NZ,PE,PL,PS,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,TW,UA,UK,UM,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } +apple_pay = { country = "AE,AM,AR,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CN,CO,CR,CY,CZ,DE,DK,EE,ES,FI,FO,FR,GB,GE,GG,GL,GR,HK,HR,HU,IE,IL,IM,IS,IT,JE,JO,JP,KW,KZ,LI,LT,LU,LV,MC,MD,ME,MO,MT,MX,MY,NL,NO,NZ,PE,PL,PS,PT,QA,RO,RS,SA,SE,SG,SI,SK,SM,TW,UA,GB,UM,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } atome = { country = "MY,SG", currency = "MYR,SGD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } bca_bank_transfer = { country = "ID", currency = "IDR" } bizum = { country = "ES", currency = "EUR" } @@ -178,11 +178,11 @@ family_mart = { country = "JP", currency = "JPY" } gcash = { country = "PH", currency = "PHP" } giropay = { country = "DE", currency = "EUR" } go_pay = { country = "ID", currency = "IDR" } -google_pay = { country = "AE,AG,AL,AO,AR,AS,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CL,CO,CY,CZ,DE,DK,DO,DZ,EE,EG,ES,FI,FR,GB,GR,HK,HR,HU,ID,IE,IL,IN,IS,IT,JO,JP,KE,KW,KZ,LB,LI,LK,LT,LU,LV,MT,MX,MY,NL,NO,NZ,OM,PA,PE,PH,PK,PL,PT,QA,RO,RU,SA,SE,SG,SI,SK,TH,TR,TW,UA,UK,US,UY,VN,ZA", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AE,AG,AL,AO,AR,AS,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CL,CO,CY,CZ,DE,DK,DO,DZ,EE,EG,ES,FI,FR,GB,GR,HK,HR,HU,ID,IE,IL,IN,IS,IT,JO,JP,KE,KW,KZ,LB,LI,LK,LT,LU,LV,MT,MX,MY,NL,NO,NZ,OM,PA,PE,PH,PK,PL,PT,QA,RO,RU,SA,SE,SG,SI,SK,TH,TR,TW,UA,GB,US,UY,VN,ZA", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,BE,CA,CH,DE,DK,ES,FI,FR,GB,IE,IT,NL,NO,PL,PT,SE,UK,US", currency = "AUD,CAD,CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD" } +klarna = { country = "AT,BE,CA,CH,DE,DK,ES,FI,FR,GB,IE,IT,NL,NO,PL,PT,SE,GB,US", currency = "AUD,CAD,CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD" } lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -200,20 +200,20 @@ open_banking_uk = { country = "GB", currency = "GBP" } oxxo = { country = "MX", currency = "MXN" } pay_bright = { country = "CA", currency = "CAD" } pay_easy = { country = "JP", currency = "JPY" } -pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE,UK", currency = "EUR" } +sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE,GB", currency = "EUR" } swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } twint = { country = "CH", currency = "CHF" } vipps = { country = "NO", currency = "NOK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 01616f3ecd0..abacd3ba5a1 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -4,7 +4,7 @@ eps.stripe.banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" -online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" online_banking_poland.adyen.banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,bank_pekaosa,bank_millennium,pay_with_alior_bank,banki_spoldzielcze,pay_with_inteligo,bnp_paribas_poland,bank_nowy_sa,credit_agricole,pay_with_bos,pay_with_citi_handlowy,pay_with_plus_bank,toyota_bank,velo_bank,e_transfer_pocztowy24" online_banking_slovakia.adyen.banks = "e_platby_vub,postova_banka,sporo_pay,tatra_pay,viamo" online_banking_thailand.adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" @@ -127,17 +127,17 @@ payout_eligibility = true [pm_filters.default] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AED,AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } blik = { country = "PL", currency = "PLN" } eps = { country = "AT", currency = "EUR" } giropay = { country = "DE", currency = "EUR" } -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } mb_way = { country = "PT", currency = "EUR" } mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } online_banking_czech_republic = { country = "CZ", currency = "EUR,CZK" } @@ -145,24 +145,24 @@ online_banking_finland = { country = "FI", currency = "EUR" } online_banking_poland = { country = "PL", currency = "PLN" } online_banking_slovakia = { country = "SK", currency = "EUR,CZK" } pay_bright = { country = "CA", currency = "CAD" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } [pm_filters.adyen] ach = { country = "US", currency = "USD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } alfamart = { country = "ID", currency = "IDR" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } ali_pay_hk = { country = "HK", currency = "HKD" } alma = { country = "FR", currency = "EUR" } -apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,UK,SE,NO,AK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } +apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,GB,SE,NO,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } atome = { country = "MY,SG", currency = "MYR,SGD" } -bacs = { country = "UK", currency = "GBP" } +bacs = { country = "GB", currency = "GBP" } bancontact_card = { country = "BE", currency = "EUR" } bca_bank_transfer = { country = "ID", currency = "IDR" } bizum = { country = "ES", currency = "EUR" } @@ -178,11 +178,11 @@ family_mart = { country = "JP", currency = "JPY" } gcash = { country = "PH", currency = "PHP" } giropay = { country = "DE", currency = "EUR" } go_pay = { country = "ID", currency = "IDR" } -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } ideal = { country = "NL", currency = "EUR" } indomaret = { country = "ID", currency = "IDR" } kakao_pay = { country = "KR", currency = "KRW" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } lawson = { country = "JP", currency = "JPY" } mandiri_va = { country = "ID", currency = "IDR" } mb_way = { country = "PT", currency = "EUR" } @@ -200,20 +200,20 @@ open_banking_uk = { country = "GB", currency = "GBP" } oxxo = { country = "MX", currency = "MXN" } pay_bright = { country = "CA", currency = "CAD" } pay_easy = { country = "JP", currency = "JPY" } -pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } permata_bank_transfer = { country = "ID", currency = "IDR" } seicomart = { country = "JP", currency = "JPY" } sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" } seven_eleven = { country = "JP", currency = "JPY" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } swish = { country = "SE", currency = "SEK" } touch_n_go = { country = "MY", currency = "MYR" } -trustly = { country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } +trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" } twint = { country = "CH", currency = "CHF" } vipps = { country = "NO", currency = "NOK" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } [pm_filters.authorizedotnet] google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" diff --git a/config/development.toml b/config/development.toml index b23f68680e6..15366986db5 100644 --- a/config/development.toml +++ b/config/development.toml @@ -263,7 +263,7 @@ stripe = { banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,ba adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled"} [bank_config.online_banking_fpx] -adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" [bank_config.online_banking_thailand] adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" @@ -293,31 +293,31 @@ ideal = { country = "NL", currency = "EUR" } cashapp = { country = "US", currency = "USD" } [pm_filters.adyen] -google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,ISK,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VEF,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } -apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,UK,SE,NO,AK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } -paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,UK,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } +google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" } +apple_pay = { country = "AU,NZ,CN,JP,HK,SG,MY,BH,AE,KW,BR,ES,GB,SE,NO,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,LI,UA,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" } +paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" } mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" } -ali_pay = { country = "AU,N,JP,HK,SG,MY,TH,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } -we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,UK,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } +ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" } +we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" } mb_way = { country = "PT", currency = "EUR" } -klarna = { country = "AT,ES,UK,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } +klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" } affirm = { country = "US", currency = "USD" } -afterpay_clearpay = { country = "AU,NZ,ES,UK,FR,IT,CA,US", currency = "GBP" } +afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" } pay_bright = { country = "CA", currency = "CAD" } walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" } giropay = { country = "DE", currency = "EUR" } eps = { country = "AT", currency = "EUR" } -sofort = { country = "ES,UK,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } +sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" } ideal = { country = "NL", currency = "EUR" } blik = {country = "PL", currency = "PLN"} -trustly = {country = "ES,UK,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"} +trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"} online_banking_czech_republic = {country = "CZ", currency = "EUR,CZK"} online_banking_finland = {country = "FI", currency = "EUR"} online_banking_poland = {country = "PL", currency = "PLN"} online_banking_slovakia = {country = "SK", currency = "EUR,CZK"} bancontact_card = {country = "BE", currency = "EUR"} ach = {country = "US", currency = "USD"} -bacs = {country = "UK", currency = "GBP"} +bacs = {country = "GB", currency = "GBP"} sepa = {country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR"} ali_pay_hk = {country = "HK", currency = "HKD"} bizum = {country = "ES", currency = "EUR"} @@ -341,7 +341,7 @@ alfamart = {country = "ID", currency = "IDR"} indomaret = {country = "ID", currency = "IDR"} open_banking_uk = {country = "GB", currency = "GBP"} oxxo = {country = "MX", currency = "MXN"} -pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} +pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} seven_eleven = {country = "JP", currency = "JPY"} lawson = {country = "JP", currency = "JPY"} mini_stop = {country = "JP", currency = "JPY"} diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 8af1528e177..7ad4f6e62ca 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -286,7 +286,7 @@ alfamart = {country = "ID", currency = "IDR"} indomaret = {country = "ID", currency = "IDR"} open_banking_uk = {country = "GB", currency = "GBP"} oxxo = {country = "MX", currency = "MXN"} -pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,UAE,UK,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,ISK,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} +pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"} seven_eleven = {country = "JP", currency = "JPY"} lawson = {country = "JP", currency = "JPY"} mini_stop = {country = "JP", currency = "JPY"} @@ -322,7 +322,7 @@ debit = { currency = "USD" } ach = { currency = "USD" } [bank_config.online_banking_fpx] -adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,may_bank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" +adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" [bank_config.online_banking_thailand] adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank" diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 949cc2e0034..6cf125be5cd 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -387,12 +387,15 @@ pub enum Currency { ALL, AMD, ANG, + AOA, ARS, AUD, AWG, AZN, + BAM, BBD, BDT, + BGN, BHD, BIF, BMD, @@ -401,6 +404,7 @@ pub enum Currency { BRL, BSD, BWP, + BYN, BZD, CAD, CHF, @@ -409,6 +413,7 @@ pub enum Currency { COP, CRC, CUP, + CVE, CZK, DJF, DKK, @@ -418,7 +423,9 @@ pub enum Currency { ETB, EUR, FJD, + FKP, GBP, + GEL, GHS, GIP, GMD, @@ -433,6 +440,7 @@ pub enum Currency { IDR, ILS, INR, + IQD, JMD, JOD, JPY, @@ -449,6 +457,7 @@ pub enum Currency { LKR, LRD, LSL, + LYD, MAD, MDL, MGA, @@ -456,11 +465,13 @@ pub enum Currency { MMK, MNT, MOP, + MRU, MUR, MVR, MWK, MXN, MYR, + MZN, NAD, NGN, NIO, @@ -468,6 +479,7 @@ pub enum Currency { NPR, NZD, OMR, + PAB, PEN, PGK, PHP, @@ -476,34 +488,47 @@ pub enum Currency { PYG, QAR, RON, + RSD, RUB, RWF, SAR, + SBD, SCR, SEK, SGD, + SHP, + SLE, SLL, SOS, + SRD, SSP, + STN, SVC, SZL, THB, + TND, + TOP, TRY, TTD, TWD, TZS, + UAH, UGX, #[default] USD, UYU, UZS, + VES, VND, VUV, + WST, XAF, + XCD, XOF, XPF, YER, ZAR, + ZMW, } impl Currency { @@ -560,12 +585,15 @@ impl Currency { Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", + Self::AOA => "973", Self::ARS => "032", Self::AUD => "036", Self::AWG => "533", Self::AZN => "944", + Self::BAM => "977", Self::BBD => "052", Self::BDT => "050", + Self::BGN => "975", Self::BHD => "048", Self::BIF => "108", Self::BMD => "060", @@ -574,6 +602,7 @@ impl Currency { Self::BRL => "986", Self::BSD => "044", Self::BWP => "072", + Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", Self::CHF => "756", @@ -581,6 +610,7 @@ impl Currency { Self::COP => "170", Self::CRC => "188", Self::CUP => "192", + Self::CVE => "132", Self::CZK => "203", Self::DJF => "262", Self::DKK => "208", @@ -590,7 +620,9 @@ impl Currency { Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", + Self::FKP => "238", Self::GBP => "826", + Self::GEL => "981", Self::GHS => "936", Self::GIP => "292", Self::GMD => "270", @@ -605,6 +637,7 @@ impl Currency { Self::IDR => "360", Self::ILS => "376", Self::INR => "356", + Self::IQD => "368", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", @@ -621,6 +654,7 @@ impl Currency { Self::LKR => "144", Self::LRD => "430", Self::LSL => "426", + Self::LYD => "434", Self::MAD => "504", Self::MDL => "498", Self::MGA => "969", @@ -628,11 +662,13 @@ impl Currency { Self::MMK => "104", Self::MNT => "496", Self::MOP => "446", + Self::MRU => "929", Self::MUR => "480", Self::MVR => "462", Self::MWK => "454", Self::MXN => "484", Self::MYR => "458", + Self::MZN => "943", Self::NAD => "516", Self::NGN => "566", Self::NIO => "558", @@ -640,6 +676,7 @@ impl Currency { Self::NPR => "524", Self::NZD => "554", Self::OMR => "512", + Self::PAB => "590", Self::PEN => "604", Self::PGK => "598", Self::PHP => "608", @@ -649,33 +686,46 @@ impl Currency { Self::QAR => "634", Self::RON => "946", Self::CNY => "156", + Self::RSD => "941", Self::RUB => "643", Self::RWF => "646", Self::SAR => "682", + Self::SBD => "090", Self::SCR => "690", Self::SEK => "752", Self::SGD => "702", + Self::SHP => "654", + Self::SLE => "925", Self::SLL => "694", Self::SOS => "706", + Self::SRD => "968", Self::SSP => "728", + Self::STN => "930", Self::SVC => "222", Self::SZL => "748", Self::THB => "764", + Self::TND => "788", + Self::TOP => "776", Self::TRY => "949", Self::TTD => "780", Self::TWD => "901", Self::TZS => "834", + Self::UAH => "980", Self::UGX => "800", Self::USD => "840", Self::UYU => "858", Self::UZS => "860", + Self::VES => "928", Self::VND => "704", Self::VUV => "548", + Self::WST => "882", Self::XAF => "950", + Self::XCD => "951", Self::XOF => "952", Self::XPF => "953", Self::YER => "886", Self::ZAR => "710", + Self::ZMW => "967", } } @@ -701,12 +751,15 @@ impl Currency { | Self::ALL | Self::AMD | Self::ANG + | Self::AOA | Self::ARS | Self::AUD | Self::AWG | Self::AZN + | Self::BAM | Self::BBD | Self::BDT + | Self::BGN | Self::BHD | Self::BMD | Self::BND @@ -714,6 +767,7 @@ impl Currency { | Self::BRL | Self::BSD | Self::BWP + | Self::BYN | Self::BZD | Self::CAD | Self::CHF @@ -721,6 +775,7 @@ impl Currency { | Self::COP | Self::CRC | Self::CUP + | Self::CVE | Self::CZK | Self::DKK | Self::DOP @@ -729,7 +784,9 @@ impl Currency { | Self::ETB | Self::EUR | Self::FJD + | Self::FKP | Self::GBP + | Self::GEL | Self::GHS | Self::GIP | Self::GMD @@ -743,6 +800,7 @@ impl Currency { | Self::IDR | Self::ILS | Self::INR + | Self::IQD | Self::JMD | Self::JOD | Self::KES @@ -756,17 +814,20 @@ impl Currency { | Self::LKR | Self::LRD | Self::LSL + | Self::LYD | Self::MAD | Self::MDL | Self::MKD | Self::MMK | Self::MNT | Self::MOP + | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR + | Self::MZN | Self::NAD | Self::NGN | Self::NIO @@ -774,6 +835,7 @@ impl Currency { | Self::NPR | Self::NZD | Self::OMR + | Self::PAB | Self::PEN | Self::PGK | Self::PHP @@ -781,42 +843,60 @@ impl Currency { | Self::PLN | Self::QAR | Self::RON + | Self::RSD | Self::RUB | Self::SAR + | Self::SBD | Self::SCR | Self::SEK | Self::SGD + | Self::SHP + | Self::SLE | Self::SLL | Self::SOS + | Self::SRD | Self::SSP + | Self::STN | Self::SVC | Self::SZL | Self::THB + | Self::TND + | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS + | Self::UAH | Self::USD | Self::UYU | Self::UZS + | Self::VES + | Self::WST + | Self::XCD | Self::YER - | Self::ZAR => false, + | Self::ZAR + | Self::ZMW => false, } } pub fn is_three_decimal_currency(self) -> bool { match self { - Self::BHD | Self::JOD | Self::KWD | Self::OMR => true, + Self::BHD | Self::IQD | Self::JOD | Self::KWD | Self::LYD | Self::OMR | Self::TND => { + true + } Self::AED | Self::ALL | Self::AMD + | Self::AOA | Self::ANG | Self::ARS | Self::AUD | Self::AWG | Self::AZN + | Self::BAM | Self::BBD | Self::BDT + | Self::BGN | Self::BIF | Self::BMD | Self::BND @@ -824,6 +904,7 @@ impl Currency { | Self::BRL | Self::BSD | Self::BWP + | Self::BYN | Self::BZD | Self::CAD | Self::CHF @@ -832,6 +913,7 @@ impl Currency { | Self::COP | Self::CRC | Self::CUP + | Self::CVE | Self::CZK | Self::DJF | Self::DKK @@ -841,7 +923,9 @@ impl Currency { | Self::ETB | Self::EUR | Self::FJD + | Self::FKP | Self::GBP + | Self::GEL | Self::GHS | Self::GIP | Self::GMD @@ -877,17 +961,20 @@ impl Currency { | Self::MMK | Self::MNT | Self::MOP + | Self::MRU | Self::MUR | Self::MVR | Self::MWK | Self::MXN | Self::MYR + | Self::MZN | Self::NAD | Self::NGN | Self::NIO | Self::NOK | Self::NPR | Self::NZD + | Self::PAB | Self::PEN | Self::PGK | Self::PHP @@ -896,33 +983,45 @@ impl Currency { | Self::PYG | Self::QAR | Self::RON + | Self::RSD | Self::RUB | Self::RWF | Self::SAR + | Self::SBD | Self::SCR | Self::SEK | Self::SGD + | Self::SHP + | Self::SLE | Self::SLL | Self::SOS + | Self::SRD | Self::SSP + | Self::STN | Self::SVC | Self::SZL | Self::THB + | Self::TOP | Self::TRY | Self::TTD | Self::TWD | Self::TZS + | Self::UAH | Self::UGX | Self::USD | Self::UYU | Self::UZS + | Self::VES | Self::VND | Self::VUV + | Self::WST | Self::XAF + | Self::XCD | Self::XPF | Self::XOF | Self::YER - | Self::ZAR => false, + | Self::ZAR + | Self::ZMW => false, } } } diff --git a/crates/currency_conversion/Cargo.toml b/crates/currency_conversion/Cargo.toml index d84956fe2f7..d2c99080bf6 100644 --- a/crates/currency_conversion/Cargo.toml +++ b/crates/currency_conversion/Cargo.toml @@ -11,6 +11,6 @@ common_enums = { version = "0.1.0", path = "../common_enums", package = "common_ # Third party crates rust_decimal = "1.29" -rusty-money = { version = "0.4.0", features = ["iso", "crypto"] } +rusty-money = { git = "https://github.com/varunsrin/rusty_money", rev = "bbc0150742a0fff905225ff11ee09388e9babdcc", features = ["iso", "crypto"] } serde = { version = "1.0.193", features = ["derive"] } thiserror = "1.0.43" diff --git a/crates/currency_conversion/src/types.rs b/crates/currency_conversion/src/types.rs index fec25b9fc60..a84520dca0a 100644 --- a/crates/currency_conversion/src/types.rs +++ b/crates/currency_conversion/src/types.rs @@ -81,12 +81,15 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::ALL => iso::ALL, Currency::AMD => iso::AMD, Currency::ANG => iso::ANG, + Currency::AOA => iso::AOA, Currency::ARS => iso::ARS, Currency::AUD => iso::AUD, Currency::AWG => iso::AWG, Currency::AZN => iso::AZN, + Currency::BAM => iso::BAM, Currency::BBD => iso::BBD, Currency::BDT => iso::BDT, + Currency::BGN => iso::BGN, Currency::BHD => iso::BHD, Currency::BIF => iso::BIF, Currency::BMD => iso::BMD, @@ -95,6 +98,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::BRL => iso::BRL, Currency::BSD => iso::BSD, Currency::BWP => iso::BWP, + Currency::BYN => iso::BYN, Currency::BZD => iso::BZD, Currency::CAD => iso::CAD, Currency::CHF => iso::CHF, @@ -103,6 +107,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::COP => iso::COP, Currency::CRC => iso::CRC, Currency::CUP => iso::CUP, + Currency::CVE => iso::CVE, Currency::CZK => iso::CZK, Currency::DJF => iso::DJF, Currency::DKK => iso::DKK, @@ -112,7 +117,9 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::ETB => iso::ETB, Currency::EUR => iso::EUR, Currency::FJD => iso::FJD, + Currency::FKP => iso::FKP, Currency::GBP => iso::GBP, + Currency::GEL => iso::GEL, Currency::GHS => iso::GHS, Currency::GIP => iso::GIP, Currency::GMD => iso::GMD, @@ -127,6 +134,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::IDR => iso::IDR, Currency::ILS => iso::ILS, Currency::INR => iso::INR, + Currency::IQD => iso::IQD, Currency::JMD => iso::JMD, Currency::JOD => iso::JOD, Currency::JPY => iso::JPY, @@ -143,6 +151,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::LKR => iso::LKR, Currency::LRD => iso::LRD, Currency::LSL => iso::LSL, + Currency::LYD => iso::LYD, Currency::MAD => iso::MAD, Currency::MDL => iso::MDL, Currency::MGA => iso::MGA, @@ -150,11 +159,13 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::MMK => iso::MMK, Currency::MNT => iso::MNT, Currency::MOP => iso::MOP, + Currency::MRU => iso::MRU, Currency::MUR => iso::MUR, Currency::MVR => iso::MVR, Currency::MWK => iso::MWK, Currency::MXN => iso::MXN, Currency::MYR => iso::MYR, + Currency::MZN => iso::MZN, Currency::NAD => iso::NAD, Currency::NGN => iso::NGN, Currency::NIO => iso::NIO, @@ -162,6 +173,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::NPR => iso::NPR, Currency::NZD => iso::NZD, Currency::OMR => iso::OMR, + Currency::PAB => iso::PAB, Currency::PEN => iso::PEN, Currency::PGK => iso::PGK, Currency::PHP => iso::PHP, @@ -170,32 +182,45 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::PYG => iso::PYG, Currency::QAR => iso::QAR, Currency::RON => iso::RON, + Currency::RSD => iso::RSD, Currency::RUB => iso::RUB, Currency::RWF => iso::RWF, Currency::SAR => iso::SAR, + Currency::SBD => iso::SBD, Currency::SCR => iso::SCR, Currency::SEK => iso::SEK, Currency::SGD => iso::SGD, + Currency::SHP => iso::SHP, + Currency::SLE => iso::SLE, Currency::SLL => iso::SLL, Currency::SOS => iso::SOS, + Currency::SRD => iso::SRD, Currency::SSP => iso::SSP, + Currency::STN => iso::STN, Currency::SVC => iso::SVC, Currency::SZL => iso::SZL, Currency::THB => iso::THB, + Currency::TND => iso::TND, + Currency::TOP => iso::TOP, Currency::TTD => iso::TTD, Currency::TRY => iso::TRY, Currency::TWD => iso::TWD, Currency::TZS => iso::TZS, + Currency::UAH => iso::UAH, Currency::UGX => iso::UGX, Currency::USD => iso::USD, Currency::UYU => iso::UYU, Currency::UZS => iso::UZS, + Currency::VES => iso::VES, Currency::VND => iso::VND, Currency::VUV => iso::VUV, + Currency::WST => iso::WST, Currency::XAF => iso::XAF, + Currency::XCD => iso::XCD, Currency::XOF => iso::XOF, Currency::XPF => iso::XPF, Currency::YER => iso::YER, Currency::ZAR => iso::ZAR, + Currency::ZMW => iso::ZMW, } } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index b1636418aa1..5bcb64fd875 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -312,12 +312,15 @@ impl IntoDirValue for api_enums::Currency { Self::ALL => Ok(dirval!(PaymentCurrency = ALL)), Self::AMD => Ok(dirval!(PaymentCurrency = AMD)), Self::ANG => Ok(dirval!(PaymentCurrency = ANG)), + Self::AOA => Ok(dirval!(PaymentCurrency = AOA)), Self::ARS => Ok(dirval!(PaymentCurrency = ARS)), Self::AUD => Ok(dirval!(PaymentCurrency = AUD)), Self::AWG => Ok(dirval!(PaymentCurrency = AWG)), Self::AZN => Ok(dirval!(PaymentCurrency = AZN)), + Self::BAM => Ok(dirval!(PaymentCurrency = BAM)), Self::BBD => Ok(dirval!(PaymentCurrency = BBD)), Self::BDT => Ok(dirval!(PaymentCurrency = BDT)), + Self::BGN => Ok(dirval!(PaymentCurrency = BGN)), Self::BHD => Ok(dirval!(PaymentCurrency = BHD)), Self::BIF => Ok(dirval!(PaymentCurrency = BIF)), Self::BMD => Ok(dirval!(PaymentCurrency = BMD)), @@ -326,6 +329,7 @@ impl IntoDirValue for api_enums::Currency { Self::BRL => Ok(dirval!(PaymentCurrency = BRL)), Self::BSD => Ok(dirval!(PaymentCurrency = BSD)), Self::BWP => Ok(dirval!(PaymentCurrency = BWP)), + Self::BYN => Ok(dirval!(PaymentCurrency = BYN)), Self::BZD => Ok(dirval!(PaymentCurrency = BZD)), Self::CAD => Ok(dirval!(PaymentCurrency = CAD)), Self::CHF => Ok(dirval!(PaymentCurrency = CHF)), @@ -334,6 +338,7 @@ impl IntoDirValue for api_enums::Currency { Self::COP => Ok(dirval!(PaymentCurrency = COP)), Self::CRC => Ok(dirval!(PaymentCurrency = CRC)), Self::CUP => Ok(dirval!(PaymentCurrency = CUP)), + Self::CVE => Ok(dirval!(PaymentCurrency = CVE)), Self::CZK => Ok(dirval!(PaymentCurrency = CZK)), Self::DJF => Ok(dirval!(PaymentCurrency = DJF)), Self::DKK => Ok(dirval!(PaymentCurrency = DKK)), @@ -343,7 +348,9 @@ impl IntoDirValue for api_enums::Currency { Self::ETB => Ok(dirval!(PaymentCurrency = ETB)), Self::EUR => Ok(dirval!(PaymentCurrency = EUR)), Self::FJD => Ok(dirval!(PaymentCurrency = FJD)), + Self::FKP => Ok(dirval!(PaymentCurrency = FKP)), Self::GBP => Ok(dirval!(PaymentCurrency = GBP)), + Self::GEL => Ok(dirval!(PaymentCurrency = GEL)), Self::GHS => Ok(dirval!(PaymentCurrency = GHS)), Self::GIP => Ok(dirval!(PaymentCurrency = GIP)), Self::GMD => Ok(dirval!(PaymentCurrency = GMD)), @@ -358,6 +365,7 @@ impl IntoDirValue for api_enums::Currency { Self::IDR => Ok(dirval!(PaymentCurrency = IDR)), Self::ILS => Ok(dirval!(PaymentCurrency = ILS)), Self::INR => Ok(dirval!(PaymentCurrency = INR)), + Self::IQD => Ok(dirval!(PaymentCurrency = IQD)), Self::JMD => Ok(dirval!(PaymentCurrency = JMD)), Self::JOD => Ok(dirval!(PaymentCurrency = JOD)), Self::JPY => Ok(dirval!(PaymentCurrency = JPY)), @@ -374,6 +382,7 @@ impl IntoDirValue for api_enums::Currency { Self::LKR => Ok(dirval!(PaymentCurrency = LKR)), Self::LRD => Ok(dirval!(PaymentCurrency = LRD)), Self::LSL => Ok(dirval!(PaymentCurrency = LSL)), + Self::LYD => Ok(dirval!(PaymentCurrency = LYD)), Self::MAD => Ok(dirval!(PaymentCurrency = MAD)), Self::MDL => Ok(dirval!(PaymentCurrency = MDL)), Self::MGA => Ok(dirval!(PaymentCurrency = MGA)), @@ -381,11 +390,13 @@ impl IntoDirValue for api_enums::Currency { Self::MMK => Ok(dirval!(PaymentCurrency = MMK)), Self::MNT => Ok(dirval!(PaymentCurrency = MNT)), Self::MOP => Ok(dirval!(PaymentCurrency = MOP)), + Self::MRU => Ok(dirval!(PaymentCurrency = MRU)), Self::MUR => Ok(dirval!(PaymentCurrency = MUR)), Self::MVR => Ok(dirval!(PaymentCurrency = MVR)), Self::MWK => Ok(dirval!(PaymentCurrency = MWK)), Self::MXN => Ok(dirval!(PaymentCurrency = MXN)), Self::MYR => Ok(dirval!(PaymentCurrency = MYR)), + Self::MZN => Ok(dirval!(PaymentCurrency = MZN)), Self::NAD => Ok(dirval!(PaymentCurrency = NAD)), Self::NGN => Ok(dirval!(PaymentCurrency = NGN)), Self::NIO => Ok(dirval!(PaymentCurrency = NIO)), @@ -393,6 +404,7 @@ impl IntoDirValue for api_enums::Currency { Self::NPR => Ok(dirval!(PaymentCurrency = NPR)), Self::NZD => Ok(dirval!(PaymentCurrency = NZD)), Self::OMR => Ok(dirval!(PaymentCurrency = OMR)), + Self::PAB => Ok(dirval!(PaymentCurrency = PAB)), Self::PEN => Ok(dirval!(PaymentCurrency = PEN)), Self::PGK => Ok(dirval!(PaymentCurrency = PGK)), Self::PHP => Ok(dirval!(PaymentCurrency = PHP)), @@ -401,33 +413,46 @@ impl IntoDirValue for api_enums::Currency { Self::PYG => Ok(dirval!(PaymentCurrency = PYG)), Self::QAR => Ok(dirval!(PaymentCurrency = QAR)), Self::RON => Ok(dirval!(PaymentCurrency = RON)), + Self::RSD => Ok(dirval!(PaymentCurrency = RSD)), Self::RUB => Ok(dirval!(PaymentCurrency = RUB)), Self::RWF => Ok(dirval!(PaymentCurrency = RWF)), Self::SAR => Ok(dirval!(PaymentCurrency = SAR)), + Self::SBD => Ok(dirval!(PaymentCurrency = SBD)), Self::SCR => Ok(dirval!(PaymentCurrency = SCR)), Self::SEK => Ok(dirval!(PaymentCurrency = SEK)), Self::SGD => Ok(dirval!(PaymentCurrency = SGD)), + Self::SHP => Ok(dirval!(PaymentCurrency = SHP)), + Self::SLE => Ok(dirval!(PaymentCurrency = SLE)), Self::SLL => Ok(dirval!(PaymentCurrency = SLL)), Self::SOS => Ok(dirval!(PaymentCurrency = SOS)), + Self::SRD => Ok(dirval!(PaymentCurrency = SRD)), Self::SSP => Ok(dirval!(PaymentCurrency = SSP)), + Self::STN => Ok(dirval!(PaymentCurrency = STN)), Self::SVC => Ok(dirval!(PaymentCurrency = SVC)), Self::SZL => Ok(dirval!(PaymentCurrency = SZL)), Self::THB => Ok(dirval!(PaymentCurrency = THB)), + Self::TND => Ok(dirval!(PaymentCurrency = TND)), + Self::TOP => Ok(dirval!(PaymentCurrency = TOP)), Self::TRY => Ok(dirval!(PaymentCurrency = TRY)), Self::TTD => Ok(dirval!(PaymentCurrency = TTD)), Self::TWD => Ok(dirval!(PaymentCurrency = TWD)), Self::TZS => Ok(dirval!(PaymentCurrency = TZS)), + Self::UAH => Ok(dirval!(PaymentCurrency = UAH)), Self::UGX => Ok(dirval!(PaymentCurrency = UGX)), Self::USD => Ok(dirval!(PaymentCurrency = USD)), Self::UYU => Ok(dirval!(PaymentCurrency = UYU)), Self::UZS => Ok(dirval!(PaymentCurrency = UZS)), + Self::VES => Ok(dirval!(PaymentCurrency = VES)), Self::VND => Ok(dirval!(PaymentCurrency = VND)), Self::VUV => Ok(dirval!(PaymentCurrency = VUV)), + Self::WST => Ok(dirval!(PaymentCurrency = WST)), Self::XAF => Ok(dirval!(PaymentCurrency = XAF)), + Self::XCD => Ok(dirval!(PaymentCurrency = XCD)), Self::XOF => Ok(dirval!(PaymentCurrency = XOF)), Self::XPF => Ok(dirval!(PaymentCurrency = XPF)), Self::YER => Ok(dirval!(PaymentCurrency = YER)), Self::ZAR => Ok(dirval!(PaymentCurrency = ZAR)), + Self::ZMW => Ok(dirval!(PaymentCurrency = ZMW)), } } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 3c1d9f7d397..f186af60a9b 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -1,7 +1,6 @@ use std::{ collections::{HashMap, HashSet}, path::PathBuf, - str::FromStr, }; #[cfg(feature = "olap")] @@ -19,7 +18,7 @@ use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; use scheduler::SchedulerSettings; -use serde::{de::Error, Deserialize, Deserializer}; +use serde::Deserialize; use storage_impl::config::QueueStrategy; #[cfg(feature = "olap")] @@ -191,7 +190,7 @@ pub struct ApplepayMerchantConfigs { #[derive(Debug, Deserialize, Clone, Default)] pub struct MultipleApiVersionSupportedConnectors { - #[serde(deserialize_with = "connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub supported_connectors: HashSet<api_models::enums::Connector>, } @@ -205,42 +204,13 @@ pub struct TempLockerEnableConfig(pub HashMap<String, TempLockerEnablePaymentMet #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorCustomer { - #[serde(deserialize_with = "connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<api_models::enums::Connector>, #[cfg(feature = "payouts")] - #[serde(deserialize_with = "payout_connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub payout_connector_list: HashSet<api_models::enums::PayoutConnectors>, } -fn connector_deser<'a, D>( - deserializer: D, -) -> Result<HashSet<api_models::enums::Connector>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - Ok(value - .trim() - .split(',') - .flat_map(api_models::enums::Connector::from_str) - .collect()) -} - -#[cfg(feature = "payouts")] -fn payout_connector_deser<'a, D>( - deserializer: D, -) -> Result<HashSet<api_models::enums::PayoutConnectors>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - Ok(value - .trim() - .split(',') - .flat_map(api_models::enums::PayoutConnectors::from_str) - .collect()) -} - #[cfg(feature = "dummy_connector")] #[derive(Debug, Deserialize, Clone, Default)] pub struct DummyConnector { @@ -281,13 +251,13 @@ pub struct SupportedPaymentMethodTypesForMandate( #[derive(Debug, Deserialize, Clone)] pub struct SupportedConnectorsForMandate { - #[serde(deserialize_with = "connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<api_models::enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodTokenFilter { - #[serde(deserialize_with = "pm_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, pub payment_method_type: Option<PaymentMethodTypeTokenFilter>, pub long_lived_token: bool, @@ -304,7 +274,7 @@ pub enum ApplePayPreDecryptFlow { #[derive(Debug, Deserialize, Clone, Default)] pub struct TempLockerEnablePaymentMethodFilter { - #[serde(deserialize_with = "pm_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, } @@ -316,44 +286,14 @@ pub struct TempLockerEnablePaymentMethodFilter { rename_all = "snake_case" )] pub enum PaymentMethodTypeTokenFilter { - #[serde(deserialize_with = "pm_type_deser")] + #[serde(deserialize_with = "deserialize_hashset")] EnableOnly(HashSet<diesel_models::enums::PaymentMethodType>), - #[serde(deserialize_with = "pm_type_deser")] + #[serde(deserialize_with = "deserialize_hashset")] DisableOnly(HashSet<diesel_models::enums::PaymentMethodType>), #[default] AllAccepted, } -fn pm_deser<'a, D>( - deserializer: D, -) -> Result<HashSet<diesel_models::enums::PaymentMethod>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - value - .trim() - .split(',') - .map(diesel_models::enums::PaymentMethod::from_str) - .collect::<Result<_, _>>() - .map_err(D::Error::custom) -} - -fn pm_type_deser<'a, D>( - deserializer: D, -) -> Result<HashSet<diesel_models::enums::PaymentMethodType>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - value - .trim() - .split(',') - .map(diesel_models::enums::PaymentMethodType::from_str) - .collect::<Result<_, _>>() - .map_err(D::Error::custom) -} - #[derive(Debug, Deserialize, Clone, Default)] pub struct BankRedirectConfig( pub HashMap<api_models::enums::PaymentMethodType, ConnectorBankNames>, @@ -363,7 +303,7 @@ pub struct ConnectorBankNames(pub HashMap<String, BanksVector>); #[derive(Debug, Deserialize, Clone)] pub struct BanksVector { - #[serde(deserialize_with = "bank_vec_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub banks: HashSet<api_models::enums::BankNames>, } @@ -385,9 +325,9 @@ pub enum PaymentMethodFilterKey { #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CurrencyCountryFlowFilter { - #[serde(deserialize_with = "currency_set_deser")] + #[serde(deserialize_with = "deserialize_optional_hashset")] pub currency: Option<HashSet<api_models::enums::Currency>>, - #[serde(deserialize_with = "string_set_deser")] + #[serde(deserialize_with = "deserialize_optional_hashset")] pub country: Option<HashSet<api_models::enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } @@ -416,58 +356,6 @@ pub struct RequiredFieldFinal { pub common: HashMap<String, RequiredFieldInfo>, } -fn string_set_deser<'a, D>( - deserializer: D, -) -> Result<Option<HashSet<api_models::enums::CountryAlpha2>>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <Option<String>>::deserialize(deserializer)?; - Ok(value.and_then(|inner| { - let list = inner - .trim() - .split(',') - .flat_map(api_models::enums::CountryAlpha2::from_str) - .collect::<HashSet<_>>(); - match list.len() { - 0 => None, - _ => Some(list), - } - })) -} - -fn currency_set_deser<'a, D>( - deserializer: D, -) -> Result<Option<HashSet<api_models::enums::Currency>>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <Option<String>>::deserialize(deserializer)?; - Ok(value.and_then(|inner| { - let list = inner - .trim() - .split(',') - .flat_map(api_models::enums::Currency::from_str) - .collect::<HashSet<_>>(); - match list.len() { - 0 => None, - _ => Some(list), - } - })) -} - -fn bank_vec_deser<'a, D>(deserializer: D) -> Result<HashSet<api_models::enums::BankNames>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - Ok(value - .trim() - .split(',') - .flat_map(api_models::enums::BankNames::from_str) - .collect()) -} - #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct Secrets { @@ -733,13 +621,13 @@ pub struct FileUploadConfig { #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { - #[serde(deserialize_with = "deser_to_get_connectors")] + #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_delayed_session_response: HashSet<api_models::enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct WebhookSourceVerificationCall { - #[serde(deserialize_with = "connector_deser")] + #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_webhook_source_verification_call: HashSet<api_models::enums::Connector>, } @@ -756,21 +644,6 @@ pub struct ConnectorRequestReferenceIdConfig { pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>, } -fn deser_to_get_connectors<'a, D>( - deserializer: D, -) -> Result<HashSet<api_models::enums::Connector>, D::Error> -where - D: Deserializer<'a>, -{ - let value = <String>::deserialize(deserializer)?; - value - .trim() - .split(',') - .map(api_models::enums::Connector::from_str) - .collect::<Result<_, _>>() - .map_err(D::Error::custom) -} - impl Settings { pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) @@ -861,24 +734,6 @@ impl Settings { } } -#[cfg(test)] -mod payment_method_deserialization_test { - #![allow(clippy::unwrap_used)] - use serde::de::{ - value::{Error as ValueError, StrDeserializer}, - IntoDeserializer, - }; - - use super::*; - - #[test] - fn test_pm_deserializer() { - let deserializer: StrDeserializer<'_, ValueError> = "wallet,card".into_deserializer(); - let test_pm = pm_deser(deserializer); - assert!(test_pm.is_ok()) - } -} - #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Clone, Default)] pub struct Payouts { @@ -893,7 +748,7 @@ pub struct LockSettings { } impl<'de> Deserialize<'de> for LockSettings { - fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Inner { @@ -928,3 +783,124 @@ pub struct PayPalOnboarding { pub partner_id: masking::Secret<String>, pub enabled: bool, } + +fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> +where + T: Eq + std::str::FromStr + std::hash::Hash, + <T as std::str::FromStr>::Err: std::fmt::Display, +{ + let (values, errors) = value + .as_ref() + .trim() + .split(',') + .map(|s| { + T::from_str(s.trim()).map_err(|error| { + format!( + "Unable to deserialize `{}` as `{}`: {error}", + s.trim(), + std::any::type_name::<T>() + ) + }) + }) + .fold( + (HashSet::new(), Vec::new()), + |(mut values, mut errors), result| match result { + Ok(t) => { + values.insert(t); + (values, errors) + } + Err(error) => { + errors.push(error); + (values, errors) + } + }, + ); + if !errors.is_empty() { + Err(format!("Some errors occurred:\n{}", errors.join("\n"))) + } else { + Ok(values) + } +} + +fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error> +where + D: serde::Deserializer<'a>, + T: Eq + std::str::FromStr + std::hash::Hash, + <T as std::str::FromStr>::Err: std::fmt::Display, +{ + use serde::de::Error; + + deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom) +} + +fn deserialize_optional_hashset<'a, D, T>(deserializer: D) -> Result<Option<HashSet<T>>, D::Error> +where + D: serde::Deserializer<'a>, + T: Eq + std::str::FromStr + std::hash::Hash, + <T as std::str::FromStr>::Err: std::fmt::Display, +{ + use serde::de::Error; + + <Option<String>>::deserialize(deserializer).map(|value| { + value.map_or(Ok(None), |inner: String| { + let list = deserialize_hashset_inner(inner).map_err(D::Error::custom)?; + match list.len() { + 0 => Ok(None), + _ => Ok(Some(list)), + } + }) + })? +} + +#[cfg(test)] +mod hashset_deserialization_test { + #![allow(clippy::unwrap_used)] + use std::collections::HashSet; + + use serde::de::{ + value::{Error as ValueError, StrDeserializer}, + IntoDeserializer, + }; + + use super::deserialize_hashset; + + #[test] + fn test_payment_method_hashset_deserializer() { + use diesel_models::enums::PaymentMethod; + + let deserializer: StrDeserializer<'_, ValueError> = "wallet,card".into_deserializer(); + let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); + let expected_payment_methods = HashSet::from([PaymentMethod::Wallet, PaymentMethod::Card]); + + assert!(payment_methods.is_ok()); + assert_eq!(payment_methods.unwrap(), expected_payment_methods); + } + + #[test] + fn test_payment_method_hashset_deserializer_with_spaces() { + use diesel_models::enums::PaymentMethod; + + let deserializer: StrDeserializer<'_, ValueError> = + "wallet, card, bank_debit".into_deserializer(); + let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); + let expected_payment_methods = HashSet::from([ + PaymentMethod::Wallet, + PaymentMethod::Card, + PaymentMethod::BankDebit, + ]); + + assert!(payment_methods.is_ok()); + assert_eq!(payment_methods.unwrap(), expected_payment_methods); + } + + #[test] + fn test_payment_method_hashset_deserializer_error() { + use diesel_models::enums::PaymentMethod; + + let deserializer: StrDeserializer<'_, ValueError> = + "wallet, card, unknown".into_deserializer(); + let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); + + assert!(payment_methods.is_err()); + } +} diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 135ca638109..604a3c5dab3 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5062,12 +5062,15 @@ "ALL", "AMD", "ANG", + "AOA", "ARS", "AUD", "AWG", "AZN", + "BAM", "BBD", "BDT", + "BGN", "BHD", "BIF", "BMD", @@ -5076,6 +5079,7 @@ "BRL", "BSD", "BWP", + "BYN", "BZD", "CAD", "CHF", @@ -5084,6 +5088,7 @@ "COP", "CRC", "CUP", + "CVE", "CZK", "DJF", "DKK", @@ -5093,7 +5098,9 @@ "ETB", "EUR", "FJD", + "FKP", "GBP", + "GEL", "GHS", "GIP", "GMD", @@ -5108,6 +5115,7 @@ "IDR", "ILS", "INR", + "IQD", "JMD", "JOD", "JPY", @@ -5124,6 +5132,7 @@ "LKR", "LRD", "LSL", + "LYD", "MAD", "MDL", "MGA", @@ -5131,11 +5140,13 @@ "MMK", "MNT", "MOP", + "MRU", "MUR", "MVR", "MWK", "MXN", "MYR", + "MZN", "NAD", "NGN", "NIO", @@ -5143,6 +5154,7 @@ "NPR", "NZD", "OMR", + "PAB", "PEN", "PGK", "PHP", @@ -5151,33 +5163,46 @@ "PYG", "QAR", "RON", + "RSD", "RUB", "RWF", "SAR", + "SBD", "SCR", "SEK", "SGD", + "SHP", + "SLE", "SLL", "SOS", + "SRD", "SSP", + "STN", "SVC", "SZL", "THB", + "TND", + "TOP", "TRY", "TTD", "TWD", "TZS", + "UAH", "UGX", "USD", "UYU", "UZS", + "VES", "VND", "VUV", + "WST", "XAF", + "XCD", "XOF", "XPF", "YER", - "ZAR" + "ZAR", + "ZMW" ] }, "CustomerAcceptance": {
2023-12-11T11:34:43Z
## Description <!-- Describe your changes in detail --> This PR updates the application configuration deserialization logic to use a common generic function to deserialize `HashSet<T>` instead of specific ones. In addition, this PR updates the function to be more lenient in that it allows spaces around the commas for better readability. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #3466. #
98bf8f5b85d318cd6ad3c7105fdde3149a2ef8ed
Unit tests: ```shell cargo test --package router --lib --all-features -- configs::settings::hashset_deserialization_test ``` <img width="800" alt="Screenshot of unit tests run" src="https://github.com/juspay/hyperswitch/assets/22217505/ac1de2b4-f771-44c7-87a9-03e62e8904f6"> Also, ran the application with each of the modified config files to verify that the application is able to correctly deserialize the specified config entries.
[ "Cargo.lock", "config/config.example.toml", "config/deployments/integration_test.toml", "config/deployments/production.toml", "config/deployments/sandbox.toml", "config/development.toml", "config/docker_compose.toml", "crates/common_enums/src/enums.rs", "crates/currency_conversion/Cargo.toml", "cr...
juspay/hyperswitch
juspay__hyperswitch-3089
Bug: [BUG] Payment Methods List filters not conscious of zero amount setup mandate payments ### Bug Description When a payment method is enabled for a particular connector with a minimum amount of `> 0`, and a zero amount setup mandate payment intent is created, the payment method doesn't show up in the list payment methods call even though amount constraints are not eligible for setup mandate payments. ### Expected Behavior The filters for list payment methods should skip amount checks if the payment is a setup mandate payment. ### Actual Behavior The amount constraints are applied to the merchant's payment methods which cause them to not show up in the response of the list payment methods call. ### Steps To Reproduce 1. Create a Merchant Account with 1 Merchant Connector account and give minimum amount as zero for all enabled payment methods 2. Create a payment with amount = 0, confirm = false & no payment method given 3. Do a list payment methods call for the created payment intent ### Context For The Bug - ### Environment - ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 84aef952a53..aaecd86627c 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2237,7 +2237,7 @@ fn filter_amount_based(payment_method: &RequestPaymentMethodTypes, amount: Optio // (Some(amt), Some(max_amt)) => amt <= max_amt, // (_, _) => true, // }; - min_check && max_check + (min_check && max_check) || amount == Some(0) } fn filter_pm_based_on_allowed_types( @@ -2296,8 +2296,9 @@ fn filter_payment_amount_based( pm: &RequestPaymentMethodTypes, ) -> bool { let amount = payment_intent.amount; - pm.maximum_amount.map_or(true, |amt| amount < amt.into()) - && pm.minimum_amount.map_or(true, |amt| amount > amt.into()) + (pm.maximum_amount.map_or(true, |amt| amount <= amt.into()) + && pm.minimum_amount.map_or(true, |amt| amount >= amt.into())) + || payment_intent.amount == 0 } async fn filter_payment_mandate_based(
2023-12-08T06:31:09Z
## Description <!-- Describe your changes in detail --> This PR updates the List Payment Method core filters to allow payment intents with zero amount ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Payment intents with zero amount are created for setting up a mandate with the connector and thus are a valid form of connector call. #
777cd5cdc2342fb7195a06505647fa331725e1dd
1. Create a Merchant Account, 1 Merchant Connector Account 2. Create a payment with amount = 0, confirm = false & no payment method given 3. Do a list payment methods call. The returned list should include all the eligible payment methods despite the amount being 0. <img width="551" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/577f1be7-e714-4951-97ea-2277ddebce6e"> <img width="551" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/bfc67914-ee7c-4fc9-adbb-0e00ab17ff2a">
[ "crates/router/src/core/payment_methods/cards.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3065
Bug: [REFACTOR] Make the `card_holder_name` optional for card details in the payment APIs ### Description We currently have the `card_holder_name` as mandatory for cards in the payment APIs. We currently do not mandatorily collect it for every payment so this causes the SDK to have to send an empty string for payments where the card holder name is not collected. We want to refactor this to allow for `null` values to avoid the need to send empty strings for the SDK.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 93c97cbd443..b19f4d7b7db 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -682,7 +682,7 @@ pub struct Card { /// The card holder's name #[schema(value_type = String, example = "John Test")] - pub card_holder_name: Secret<String>, + pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 3c7d5f2918f..38007a3110d 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -118,7 +118,7 @@ impl From<StripeCard> for payments::Card { card_number: card.number, card_exp_month: card.exp_month, card_exp_year: card.exp_year, - card_holder_name: card.holder_name.unwrap_or("name".to_string().into()), + card_holder_name: card.holder_name, card_cvc: card.cvc, card_issuer: None, card_network: None, diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 9d3f74af8cb..4c99d0cb00b 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -95,7 +95,7 @@ impl From<StripeCard> for payments::Card { card_number: card.number, card_exp_month: card.exp_month, card_exp_year: card.exp_year, - card_holder_name: masking::Secret::new("stripe_cust".to_owned()), + card_holder_name: Some(masking::Secret::new("stripe_cust".to_owned())), card_cvc: card.cvc, card_issuer: None, card_network: None, diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 9cfb657bdca..53639f268c8 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -254,7 +254,9 @@ impl TryFrom<api_models::payments::Card> for PaymentDetails { fn try_from(card_data: api_models::payments::Card) -> Result<Self, Self::Error> { Ok(Self::AciCard(Box::new(CardDetails { card_number: card_data.card_number, - card_holder: card_data.card_holder_name, + card_holder: card_data + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, card_expiry_month: card_data.card_exp_month, card_expiry_year: card_data.card_exp_year, card_cvv: card_data.card_cvc, diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 2d50569f9a4..4729bfa5a6e 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -5,7 +5,7 @@ use masking::{PeekInterface, Secret}; use serde::{Deserialize, Deserializer, Serialize}; use crate::{ - connector::utils::{BrowserInformationData, PaymentsAuthorizeRequestData}, + connector::utils::{self, BrowserInformationData, PaymentsAuthorizeRequestData}, consts, core::errors, services, @@ -117,7 +117,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest { enums::AuthenticationType::NoThreeDs => None, }; let bambora_card = BamboraCard { - name: req_card.card_holder_name, + name: req_card + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index f6c1bfc46b0..d1201309637 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -867,7 +867,9 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest { expiration_year: card_data.card_exp_year, expiration_month: card_data.card_exp_month, cvv: card_data.card_cvc, - cardholder_name: card_data.card_holder_name, + cardholder_name: card_data + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, }, }; Ok(Self { diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 92d01cfe56d..25462c758f1 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use url::Url; use crate::{ - connector::utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, + connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, core::errors, services, types::{self, api, storage::enums}, @@ -125,7 +125,10 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP document: get_doc_from_currency(country.to_string()), }, card: Some(Card { - holder_name: ccard.card_holder_name.clone(), + holder_name: ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: ccard.card_number.clone(), cvv: ccard.card_cvc.clone(), expiration_month: ccard.card_exp_month.clone(), diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs index 3c7bd2e09d9..bbb3b10c8e0 100644 --- a/crates/router/src/connector/dummyconnector/transformers.rs +++ b/crates/router/src/connector/dummyconnector/transformers.rs @@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize}; use url::Url; use crate::{ + connector::utils, core::errors, services, types::{self, api, storage::enums}, @@ -83,15 +84,18 @@ pub struct DummyConnectorCard { cvc: Secret<String>, } -impl From<api_models::payments::Card> for DummyConnectorCard { - fn from(value: api_models::payments::Card) -> Self { - Self { - name: value.card_holder_name, +impl TryFrom<api_models::payments::Card> for DummyConnectorCard { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(value: api_models::payments::Card) -> Result<Self, Self::Error> { + Ok(Self { + name: value + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: value.card_number, expiry_month: value.card_exp_month, expiry_year: value.card_exp_year, cvc: value.card_cvc, - } + }) } } @@ -151,7 +155,7 @@ impl<const T: u8> TryFrom<&types::PaymentsAuthorizeRouterData> .payment_method_data { api::PaymentMethodData::Card(ref req_card) => { - Ok(PaymentMethodData::Card(req_card.clone().into())) + Ok(PaymentMethodData::Card(req_card.clone().try_into()?)) } api::PaymentMethodData::Wallet(ref wallet_data) => { Ok(PaymentMethodData::Wallet(wallet_data.clone().try_into()?)) diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 4bb354f6cda..411457fab67 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -82,7 +82,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { let address = item.get_billing_address()?; let card = Card { card_type, - name_on_card: ccard.card_holder_name.clone(), + name_on_card: ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, account_number: ccard.card_number.clone(), expire_month: ccard.card_exp_month.clone(), expire_year: ccard.card_exp_year.clone(), diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs index 62fb94e236a..c1151adcf6d 100644 --- a/crates/router/src/connector/mollie/transformers.rs +++ b/crates/router/src/connector/mollie/transformers.rs @@ -286,7 +286,10 @@ impl TryFrom<&types::TokenizationRouterData> for MollieCardTokenRequest { match item.request.payment_method_data.clone() { api_models::payments::PaymentMethodData::Card(ccard) => { let auth = MollieAuthType::try_from(&item.connector_auth_type)?; - let card_holder = ccard.card_holder_name.clone(); + let card_holder = ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?; let card_number = ccard.card_number.clone(); let card_expiry_date = ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned()); diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index b478d63e0f1..e2262e7b895 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -200,7 +200,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { _ => ( match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard { - name_on_card: req_card.card_holder_name.clone(), + name_on_card: req_card + .card_holder_name + .clone() + .ok_or_else(conn_utils::missing_field_err("card_holder_name"))?, number_plain: req_card.card_number.clone(), expiry_month: req_card.card_exp_month.clone(), expiry_year: req_card.get_expiry_year_4_digit(), diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 73e039c6339..4ed6b25b136 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1000,7 +1000,7 @@ impl From<NuveiCardDetails> for PaymentOption { Self { card: Some(Card { card_number: Some(card.card_number), - card_holder_name: Some(card.card_holder_name), + card_holder_name: card.card_holder_name, expiration_month: Some(card.card_exp_month), expiration_year: Some(card.card_exp_year), three_d: card_details.three_d, diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index 7b633f6aa64..a0e3877f82b 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -29,7 +29,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { match item.request.payment_method_data.clone() { api::PaymentMethodData::Card(req_card) => { let card = OpayoCard { - name: req_card.card_holder_name, + name: req_card + .card_holder_name + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: req_card.card_number, expiry_month: req_card.card_exp_month, expiry_year: req_card.card_exp_year, diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 0170d18ecb4..8b4f4a46959 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -241,7 +241,10 @@ fn get_payment_method_data( let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?; let payeezy_card = PayeezyCard { card_type, - cardholder_name: card.card_holder_name.clone(), + cardholder_name: card + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, card_number: card.card_number.clone(), exp_date: card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string()), cvv: card.card_cvc.clone(), diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 8b6a2297d09..0871bc5097a 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -443,7 +443,10 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP let payment_source = Some(PaymentSourceItem::Card(CardRequest { billing_address: get_address_info(item.router_data.address.billing.as_ref())?, expiry, - name: ccard.card_holder_name.clone(), + name: ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, number: Some(ccard.card_number.clone()), security_code: Some(ccard.card_cvc.clone()), attributes, diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index e0ecd81c7e5..6d5a756c571 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -101,7 +101,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let source = match item.request.payment_method_data.clone() { - api::PaymentMethodData::Card(card) => Ok(Source::from(&card)), + api::PaymentMethodData::Card(card) => Source::try_from(&card), api::PaymentMethodData::Wallet(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::PayLater(_) @@ -211,15 +211,19 @@ impl TryFrom<&types::BrowserInformation> for BrowserInfo { }) }*/ -impl From<&Card> for Source { - fn from(card: &Card) -> Self { +impl TryFrom<&Card> for Source { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(card: &Card) -> Result<Self, Self::Error> { let card = PowertranzCard { - cardholder_name: card.card_holder_name.clone(), + cardholder_name: card + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, card_pan: card.card_number.clone(), card_expiration: card.get_expiry_date_as_yymm(), card_cvv: card.card_cvc.clone(), }; - Self::Card(card) + Ok(Self::Card(card)) } } diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 193eb819892..aab47bc8b21 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -4,7 +4,7 @@ use time::PrimitiveDateTime; use url::Url; use crate::{ - connector::utils::PaymentsAuthorizeRequestData, + connector::utils::{self, PaymentsAuthorizeRequestData}, consts, core::errors, pii::Secret, @@ -131,7 +131,10 @@ impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPay number: ccard.card_number.to_owned(), expiration_month: ccard.card_exp_month.to_owned(), expiration_year: ccard.card_exp_year.to_owned(), - name: ccard.card_holder_name.to_owned(), + name: ccard + .card_holder_name + .to_owned() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, cvv: ccard.card_cvc.to_owned(), }), address: None, diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index ce68aad25c5..2b89e7ebf6c 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -296,7 +296,10 @@ impl<T> number: card.card_number.clone(), exp_month: card.card_exp_month.clone(), exp_year: card.card_exp_year.clone(), - cardholder_name: card.card_holder_name.clone(), + cardholder_name: card + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, }; if item.is_three_ds() { Ok(Self::Cards3DSRequest(Box::new(Cards3DSRequest { diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index 2fd3b3474ea..7395172239e 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -226,7 +226,9 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { let stax_card_data = StaxTokenizeData { card_exp: card_data .get_card_expiry_month_year_2_digit_with_delimiter("".to_string()), - person_name: card_data.card_holder_name, + person_name: card_data + .card_holder_name + .ok_or_else(missing_field_err("card_holder_name"))?, card_number: card_data.card_number, card_cvv: card_data.card_cvc, customer_id: Secret::new(customer_id), diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index b5739fe857a..d9e9d1ff7c0 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -351,7 +351,10 @@ fn make_card_request( let expiry_date: Secret<String> = Secret::new(secret_value); let card = Card { card_number: ccard.card_number.clone(), - cardholder_name: ccard.card_holder_name.clone(), + cardholder_name: ccard + .card_holder_name + .clone() + .ok_or_else(utils::missing_field_err("card_holder_name"))?, cvv: ccard.card_cvc.clone(), expiry_date, }; diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 5ad78c9d730..c71632c9b06 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -51,7 +51,10 @@ impl Vaultable for api::Card { card_number: self.card_number.peek().clone(), exp_year: self.card_exp_year.peek().clone(), exp_month: self.card_exp_month.peek().clone(), - name_on_card: Some(self.card_holder_name.peek().clone()), + name_on_card: self + .card_holder_name + .clone() + .map(|name| name.peek().clone()), nickname: None, card_last_four: None, card_token: None, @@ -99,7 +102,7 @@ impl Vaultable for api::Card { .attach_printable("Invalid card number format from the mock locker")?, card_exp_month: value1.exp_month.into(), card_exp_year: value1.exp_year.into(), - card_holder_name: value1.name_on_card.unwrap_or_default().into(), + card_holder_name: value1.name_on_card.map(masking::Secret::new), card_cvc: value2.card_security_code.unwrap_or_default().into(), card_issuer: None, card_network: None, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 4e491964e96..866a0581e4e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -946,6 +946,42 @@ pub fn verify_mandate_details( ) } +// This function validates card_holder_name field to be either null or a non-empty string +pub fn validate_card_holder_name( + payment_method_data: Option<api::PaymentMethodData>, +) -> CustomResult<(), errors::ApiErrorResponse> { + if let Some(pmd) = payment_method_data { + match pmd { + // This validation would occur during payments create + api::PaymentMethodData::Card(card) => { + if let Some(name) = &card.card_holder_name { + if name.clone().expose().is_empty() { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "card_holder_name cannot be empty".to_string(), + }) + .into_report(); + } + } + } + + // This validation would occur during payments confirm + api::PaymentMethodData::CardToken(card) => { + if let Some(name) = card.card_holder_name { + if name.expose().is_empty() { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "card_holder_name cannot be empty".to_string(), + }) + .into_report(); + } + } + } + _ => (), + } + } + + Ok(()) +} + #[instrument(skip_all)] pub fn payment_attempt_status_fsm( payment_method_data: &Option<api::PaymentMethodData>, @@ -1033,7 +1069,7 @@ pub(crate) async fn get_payment_method_create_request( card_number: card.card_number.clone(), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), - card_holder_name: Some(card.card_holder_name.clone()), + card_holder_name: card.card_holder_name.clone(), nick_name: card.nick_name.clone(), }; let customer_id = customer.customer_id.clone(); @@ -1404,21 +1440,25 @@ pub async fn retrieve_payment_method_with_temporary_token( let mut updated_card = card.clone(); let mut is_card_updated = false; - let name_on_card = if card.card_holder_name.clone().expose().is_empty() { - card_token_data - .and_then(|token_data| token_data.card_holder_name.clone()) - .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) - .map(|name_on_card| { + // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked + // from payment_method.card_token object + let name_on_card = if let Some(name) = card.card_holder_name.clone() { + if name.expose().is_empty() { + card_token_data.and_then(|token_data| { is_card_updated = true; - name_on_card + token_data.card_holder_name.clone() }) + } else { + card.card_holder_name.clone() + } } else { - Some(card.card_holder_name.clone()) + card_token_data.and_then(|token_data| { + is_card_updated = true; + token_data.card_holder_name.clone() + }) }; - if let Some(name_on_card) = name_on_card { - updated_card.card_holder_name = name_on_card; - } + updated_card.card_holder_name = name_on_card; if let Some(token_data) = card_token_data { if let Some(cvc) = token_data.card_cvc.clone() { @@ -1487,23 +1527,21 @@ pub async fn retrieve_card_with_permanent_token( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker")?; - let name_on_card = if let Some(name_on_card) = card.name_on_card.clone() { - if card.name_on_card.unwrap_or_default().expose().is_empty() { - card_token_data - .and_then(|token_data| token_data.card_holder_name.clone()) - .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) + // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked + // from payment_method.card_token object + let name_on_card = if let Some(name) = card.name_on_card.clone() { + if name.expose().is_empty() { + card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) } else { - Some(name_on_card) + card.name_on_card } } else { - card_token_data - .and_then(|token_data| token_data.card_holder_name.clone()) - .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) + card_token_data.and_then(|token_data| token_data.card_holder_name.clone()) }; let api_card = api::Card { card_number: card.card_number, - card_holder_name: name_on_card.unwrap_or(masking::Secret::from("".to_string())), + card_holder_name: name_on_card, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_cvc: card_token_data @@ -3324,7 +3362,7 @@ pub async fn get_additional_payment_data( bank_code: card_data.bank_code.to_owned(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: Some(card_data.card_holder_name.clone()), + card_holder_name: card_data.card_holder_name.clone(), last4: last4.clone(), card_isin: card_isin.clone(), }, @@ -3352,7 +3390,7 @@ pub async fn get_additional_payment_data( card_isin: card_isin.clone(), card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: Some(card_data.card_holder_name.clone()), + card_holder_name: card_data.card_holder_name.clone(), }, )) }); @@ -3367,7 +3405,7 @@ pub async fn get_additional_payment_data( card_isin, card_exp_month: Some(card_data.card_exp_month.clone()), card_exp_year: Some(card_data.card_exp_year.clone()), - card_holder_name: Some(card_data.card_holder_name.clone()), + card_holder_name: card_data.card_holder_name.clone(), }, ))) } diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index af2a9fa49c8..612ddadc1c5 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -871,6 +871,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; + helpers::validate_card_holder_name(request.payment_method_data.clone())?; + let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index eb7f31ba24d..cbce6ba9e97 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -560,6 +560,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_amount_to_capture_and_capture_method(None, request)?; helpers::validate_card_data(request.payment_method_data.clone())?; + helpers::validate_card_holder_name(request.payment_method_data.clone())?; + helpers::validate_payment_method_fields_present(request)?; let mandate_type = diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index f1a35cffce8..84f11124c73 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -655,6 +655,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; + helpers::validate_card_holder_name(request.payment_method_data.clone())?; + let mandate_type = helpers::validate_mandate(request, false)?; Ok(( diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 2acf42fa479..9159abf4bd1 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -244,7 +244,7 @@ mod payments_test { card_number: "1234432112344321".to_string().try_into().unwrap(), card_exp_month: "12".to_string().into(), card_exp_year: "99".to_string().into(), - card_holder_name: "JohnDoe".to_string().into(), + card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())), card_cvc: "123".to_string().into(), card_issuer: Some("HDFC".to_string()), card_network: Some(api_models::enums::CardNetwork::Visa), diff --git a/crates/router/src/utils/verify_connector.rs b/crates/router/src/utils/verify_connector.rs index 6ad683d63ba..060f92d0e5a 100644 --- a/crates/router/src/utils/verify_connector.rs +++ b/crates/router/src/utils/verify_connector.rs @@ -20,7 +20,7 @@ pub fn generate_card_from_details( card_network: None, card_exp_year: masking::Secret::new(card_exp_year), card_exp_month: masking::Secret::new(card_exp_month), - card_holder_name: masking::Secret::new("HyperSwitch".to_string()), + card_holder_name: Some(masking::Secret::new("HyperSwitch".to_string())), nick_name: None, card_type: None, card_issuing_country: None, diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 7ddc504956f..dd8c1ed5f77 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -38,7 +38,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("999".to_string()), card_issuer: None, card_network: None, @@ -232,7 +232,7 @@ async fn payments_create_failure() { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("99".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 714dc0d7d67..14177e6fb50 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -126,7 +126,7 @@ impl AdyenTest { card_number: cards::CardNumber::from_str(card_number).unwrap(), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new(card_cvc.to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs index 6e7f6c000d2..cfc4c0c003d 100644 --- a/crates/router/tests/connectors/airwallex.rs +++ b/crates/router/tests/connectors/airwallex.rs @@ -60,7 +60,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { card_number: cards::CardNumber::from_str("4035501000000008").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index 4021d57d543..3ae4298e836 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -42,7 +42,7 @@ fn get_payment_method_data() -> api::Card { card_number: cards::CardNumber::from_str("5424000000000015").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), ..Default::default() } diff --git a/crates/router/tests/connectors/bluesnap.rs b/crates/router/tests/connectors/bluesnap.rs index 30052d11da4..852b23f022c 100644 --- a/crates/router/tests/connectors/bluesnap.rs +++ b/crates/router/tests/connectors/bluesnap.rs @@ -400,7 +400,7 @@ async fn should_fail_payment_for_incorrect_cvc() { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), @@ -426,7 +426,7 @@ async fn should_fail_payment_for_invalid_exp_month() { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), @@ -452,7 +452,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() { Some(types::PaymentsAuthorizeData { email: Some(Email::from_str("test@gmail.com").unwrap()), payment_method_data: types::api::PaymentMethodData::Card(api::Card { - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 1394667718c..36d5f66dbcc 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -46,7 +46,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { card_number: cards::CardNumber::from_str("4005550000000019").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2035".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs index 5550ba12af8..7de81a8bed2 100644 --- a/crates/router/tests/connectors/payme.rs +++ b/crates/router/tests/connectors/payme.rs @@ -87,7 +87,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { card_cvc: Secret::new("123".to_string()), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), ..utils::CCardType::default().0 }), amount: 1000, diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index 143f87fc575..c53f4e8d8b1 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -46,7 +46,7 @@ async fn should_only_authorize_payment() { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, @@ -74,7 +74,7 @@ async fn should_authorize_and_capture_payment() { card_number: cards::CardNumber::from_str("4111111111111111").unwrap(), card_exp_month: Secret::new("02".to_string()), card_exp_year: Secret::new("2024".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("123".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 7e5cfeb4397..d3b20b01e4c 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -869,7 +869,7 @@ impl Default for CCardType { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new("999".to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index fd697f95b75..6a92e0dc93f 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -71,7 +71,7 @@ impl WorldlineTest { card_number: cards::CardNumber::from_str(card_number).unwrap(), card_exp_month: Secret::new(card_exp_month.to_string()), card_exp_year: Secret::new(card_exp_year.to_string()), - card_holder_name: Secret::new("John Doe".to_string()), + card_holder_name: Some(masking::Secret::new("John Doe".to_string())), card_cvc: Secret::new(card_cvc.to_string()), card_issuer: None, card_network: None, diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 9d48aaddd45..8f5ac25736c 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -320,7 +320,7 @@ async fn payments_create_core() { card_number: "4242424242424242".to_string().try_into().unwrap(), card_exp_month: "10".to_string().into(), card_exp_year: "35".to_string().into(), - card_holder_name: "Arun Raj".to_string().into(), + card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())), card_cvc: "123".to_string().into(), card_issuer: None, card_network: None, @@ -496,7 +496,7 @@ async fn payments_create_core_adyen_no_redirect() { card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(), card_exp_month: "03".to_string().into(), card_exp_year: "2030".to_string().into(), - card_holder_name: "JohnDoe".to_string().into(), + card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())), card_cvc: "737".to_string().into(), card_issuer: None, card_network: None, diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 42e5524a15d..89ac522d237 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -80,7 +80,7 @@ async fn payments_create_core() { card_number: "4242424242424242".to_string().try_into().unwrap(), card_exp_month: "10".to_string().into(), card_exp_year: "35".to_string().into(), - card_holder_name: "Arun Raj".to_string().into(), + card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())), card_cvc: "123".to_string().into(), card_issuer: None, card_network: None, @@ -263,7 +263,7 @@ async fn payments_create_core_adyen_no_redirect() { card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(), card_exp_month: "03".to_string().into(), card_exp_year: "2030".to_string().into(), - card_holder_name: "JohnDoe".to_string().into(), + card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())), card_cvc: "737".to_string().into(), bank_code: None, card_issuer: None,
2023-12-06T16:46:54Z
## Description <!-- Describe your changes in detail --> We currently have the `card_holder_name` as mandatory for cards in the payment APIs. We currently do not mandatorily collect it for every payment so this causes the SDK to have to send an empty string for payments where the card holder name is not collected. This PR includes following changes: * Refactoring to allow `card_holder_name` field for null values to avoid the need to send empty strings for the SDK. * Throw error when `card_holder_name` is not passed for the connector in which `card_holder_name` is a required field. * Allow sending either `null` or `non-empty string` for `card_holder_name` field. If an empty string is passed, throws an error Above changes apply during both payments `create` and `confirm` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
777cd5cdc2342fb7195a06505647fa331725e1dd
1. Create merchant account ``` curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "merchant_1701880995", "locker_id": "m0010", "merchant_name": "Chethan", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` 2. Create API key ``` curl --location 'http://localhost:8080/api_keys/merchant_1701880168' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2024-07-06T06:15:00.000Z" }' ``` 3. Create MCA account with ACI as connector (because `card_holder_name` is required field for ACI) ``` curl --location 'http://localhost:8080/account/merchant_1701880168/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "aci", "connector_account_details": { "api_key": "Bearer OGFjN2E0Yzk3ZDA0NDMwNTAxN2QwNTMxNDQxMjA5ZjF8emV6N1lTUHNEaw==", "auth_type": "BodyKey", "key1": "8ac7a4c97d044305017d053142b009ed" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "ali_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "mb_way", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "interac", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" } }' ``` 4. Make a payment without passing `card_holder_name` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_dk7ZaxtZSxglnD4CUK3R2mPZBfOczCfAytnTyZZ0gm2u5sJqLyo4w5CiEJLIRT5e' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "setup_future_usage": "on_session", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Above API should throw below error ![error](https://github.com/juspay/hyperswitch/assets/70657455/4b38f4d1-3623-4971-9673-cd19737b22fd) 5. You can check this flow for connector in which `card_holder_name` is not a required field (like stripe). In this case you need not pass the `card_holder_name` as it is made optional here. 6. If u try to make a payment with `card_holder_name` empty, it will throw below error ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_98wh5QexR03yFlBCDPr0eSkvWH69UB1DwpSQyGK9qBSMPTeo2vWBmD0D3yAHdl54' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_cvc": "123", "card_holder_name": "" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ![image](https://github.com/juspay/hyperswitch/assets/70657455/4fc50540-8e67-4d8a-a52d-0b5c4aff1786) 7. You can try above flow with `/confirm` route too ``` curl --location 'http://localhost:8080/payments/pay_QXQSt3xFUpR1DRWWkCwW/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_98wh5QexR03yFlBCDPr0eSkvWH69UB1DwpSQyGK9qBSMPTeo2vWBmD0D3yAHdl54' \ --data '{ "payment_method": "card", "payment_method_type": "credit", "payment_token": "token_WuamozY38qmQBbPXn7aS", "payment_method_data": { "card_token": { "card_holder_name": "" } } }' ```
[ "crates/api_models/src/payments.rs", "crates/router/src/compatibility/stripe/payment_intents/types.rs", "crates/router/src/compatibility/stripe/setup_intents/types.rs", "crates/router/src/connector/aci/transformers.rs", "crates/router/src/connector/bambora/transformers.rs", "crates/router/src/connector/br...
juspay/hyperswitch
juspay__hyperswitch-3070
Bug: [FEATURE] Make the Euclid Knowledge Graph generic in its supported keys & values ### Feature Description The Euclid Knowledge Graph is a framework that allows the developer to model domain specific constraints in routing, including but not limited to, general payment domain constraints (e.g.: the payment method should be card for the card type to be debit), merchant-specific constraints (e.g: Applepay is enabled for Stripe but not for Trustpay), etc. Currently the Knowledge Graph has a hard and fast dependency on the `DirValue` for modeling its constraints, which is the primary Domain Intermediate Representation type used by the Euclid Rule Engine. This causes anyone who wants to use the knowledge graph for purposes other than routing to depend on the routing module. We want to separate out the Knowledge Graph from routing and convert it into a more generic **_Constraint Graph_**. ### Possible Implementation Pull out the Knowledge Graph from Euclid into its own `constraint_graph` crate, and make the Key and Value types in the constraints generic, with the implementation having certain trait bounds on the generic types as per requirement. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index 00c491d7101..7fce1e7f538 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2677,6 +2677,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" +[[package]] +name = "erased-serde" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c138974f9d5e7fe373eb04df7cae98833802ae4b11c24ac7039a21d5af4b26c" +dependencies = [ + "serde", +] + [[package]] name = "erased-serde" version = "0.4.4" @@ -2733,10 +2742,11 @@ version = "0.1.0" dependencies = [ "common_enums", "criterion", - "erased-serde", + "erased-serde 0.4.4", "euclid_macros", "frunk", "frunk_core", + "hyperswitch_constraint_graph", "nom", "once_cell", "rustc-hash", @@ -2768,6 +2778,7 @@ dependencies = [ "currency_conversion", "euclid", "getrandom", + "hyperswitch_constraint_graph", "kgraph_utils", "once_cell", "ron-parser", @@ -3602,6 +3613,18 @@ dependencies = [ "tokio 1.37.0", ] +[[package]] +name = "hyperswitch_constraint_graph" +version = "0.1.0" +dependencies = [ + "erased-serde 0.3.31", + "rustc-hash", + "serde", + "serde_json", + "strum 0.25.0", + "thiserror", +] + [[package]] name = "hyperswitch_domain_models" version = "0.1.0" @@ -3911,6 +3934,7 @@ dependencies = [ "common_enums", "criterion", "euclid", + "hyperswitch_constraint_graph", "masking", "serde", "serde_json", @@ -4067,7 +4091,7 @@ version = "0.1.0" dependencies = [ "bytes 1.6.0", "diesel", - "erased-serde", + "erased-serde 0.4.4", "serde", "serde_json", "subtle", @@ -5599,7 +5623,7 @@ dependencies = [ "digest", "dyn-clone", "encoding_rs", - "erased-serde", + "erased-serde 0.4.4", "error-stack", "euclid", "events", @@ -5608,6 +5632,7 @@ dependencies = [ "hex", "http 0.2.12", "hyper 0.14.28", + "hyperswitch_constraint_graph", "hyperswitch_domain_models", "hyperswitch_interfaces", "image", @@ -6698,6 +6723,15 @@ dependencies = [ "strum_macros 0.24.3", ] +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +dependencies = [ + "strum_macros 0.25.3", +] + [[package]] name = "strum" version = "0.26.2" @@ -6720,6 +6754,19 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "strum_macros" +version = "0.25.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.57", +] + [[package]] name = "strum_macros" version = "0.26.2" diff --git a/crates/euclid/Cargo.toml b/crates/euclid/Cargo.toml index 7de27645523..3341746ab74 100644 --- a/crates/euclid/Cargo.toml +++ b/crates/euclid/Cargo.toml @@ -21,6 +21,7 @@ utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order # First party dependencies common_enums = { version = "0.1.0", path = "../common_enums" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } euclid_macros = { version = "0.1.0", path = "../euclid_macros" } [features] diff --git a/crates/euclid/src/dssa/analyzer.rs b/crates/euclid/src/dssa/analyzer.rs index 4c615e78495..dc1da99a832 100644 --- a/crates/euclid/src/dssa/analyzer.rs +++ b/crates/euclid/src/dssa/analyzer.rs @@ -4,11 +4,15 @@ //! in the Euclid Rule DSL. These include standard control flow analyses like testing //! conflicting assertions, to Domain Specific Analyses making use of the //! [`Knowledge Graph Framework`](crate::dssa::graph). +use hyperswitch_constraint_graph::{ConstraintGraph, Memoization}; use rustc_hash::{FxHashMap, FxHashSet}; -use super::{graph::Memoization, types::EuclidAnalysable}; use crate::{ - dssa::{graph, state_machine, truth, types}, + dssa::{ + graph::CgraphExt, + state_machine, truth, + types::{self, EuclidAnalysable}, + }, frontend::{ ast, dir::{self, EuclidDirFilter}, @@ -203,12 +207,12 @@ fn perform_condition_analyses( fn perform_context_analyses( context: &types::ConjunctiveContext<'_>, - knowledge_graph: &graph::KnowledgeGraph<'_>, + knowledge_graph: &ConstraintGraph<'_, dir::DirValue>, ) -> Result<(), types::AnalysisError> { perform_condition_analyses(context)?; let mut memo = Memoization::new(); knowledge_graph - .perform_context_analysis(context, &mut memo) + .perform_context_analysis(context, &mut memo, None) .map_err(|err| types::AnalysisError { error_type: types::AnalysisErrorType::GraphAnalysis(err, memo), metadata: Default::default(), @@ -218,7 +222,7 @@ fn perform_context_analyses( pub fn analyze<O: EuclidAnalysable + EuclidDirFilter>( program: ast::Program<O>, - knowledge_graph: Option<&graph::KnowledgeGraph<'_>>, + knowledge_graph: Option<&ConstraintGraph<'_, dir::DirValue>>, ) -> Result<vir::ValuedProgram<O>, types::AnalysisError> { let dir_program = ast::lowering::lower_program(program)?; @@ -241,9 +245,14 @@ mod tests { use std::{ops::Deref, sync::Weak}; use euclid_macros::knowledge; + use hyperswitch_constraint_graph as cgraph; use super::*; - use crate::{dirval, types::DummyOutput}; + use crate::{ + dirval, + dssa::graph::{self, euclid_graph_prelude}, + types::DummyOutput, + }; #[test] fn test_conflicting_assertion_detection() { @@ -368,7 +377,7 @@ mod tests { #[test] fn test_negation_graph_analysis() { - let graph = knowledge! {crate + let graph = knowledge! { CaptureMethod(Automatic) ->> PaymentMethod(Card); }; @@ -410,18 +419,18 @@ mod tests { .deref() .clone() { - graph::AnalysisTrace::Value { predecessors, .. } => { - let _value = graph::NodeValue::Value(dir::DirValue::PaymentMethod( + cgraph::AnalysisTrace::Value { predecessors, .. } => { + let _value = cgraph::NodeValue::Value(dir::DirValue::PaymentMethod( dir::enums::PaymentMethod::Card, )); - let _relation = graph::Relation::Positive; + let _relation = cgraph::Relation::Positive; predecessors } _ => panic!("Expected Negation Trace for payment method = card"), }; let pred = match predecessor { - Some(graph::ValueTracePredecessor::Mandatory(predecessor)) => predecessor, + Some(cgraph::error::ValueTracePredecessor::Mandatory(predecessor)) => predecessor, _ => panic!("No predecessor found"), }; assert_eq!( @@ -433,11 +442,11 @@ mod tests { *Weak::upgrade(&pred) .expect("Expected Arc not found") .deref(), - graph::AnalysisTrace::Value { - value: graph::NodeValue::Value(dir::DirValue::CaptureMethod( + cgraph::AnalysisTrace::Value { + value: cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( dir::enums::CaptureMethod::Automatic )), - relation: graph::Relation::Positive, + relation: cgraph::Relation::Positive, info: None, metadata: None, predecessors: None, diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index cb72cca0448..526248a3817 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -1,272 +1,53 @@ -use std::{ - fmt::Debug, - hash::Hash, - ops::{Deref, DerefMut}, - sync::{Arc, Weak}, -}; +use std::{fmt::Debug, sync::Weak}; -use erased_serde::{self, Serialize as ErasedSerialize}; +use hyperswitch_constraint_graph as cgraph; use rustc_hash::{FxHashMap, FxHashSet}; -use serde::Serialize; use crate::{ dssa::types, frontend::dir, types::{DataType, Metadata}, - utils, }; -#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Hash, strum::Display)] -pub enum Strength { - Weak, - Normal, - Strong, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum Relation { - Positive, - Negative, -} - -impl From<Relation> for bool { - fn from(value: Relation) -> Self { - matches!(value, Relation::Positive) - } -} - -#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Hash)] -pub struct NodeId(usize); - -impl utils::EntityId for NodeId { - #[inline] - fn get_id(&self) -> usize { - self.0 - } - - #[inline] - fn with_id(id: usize) -> Self { - Self(id) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct DomainInfo<'a> { - pub domain_identifier: DomainIdentifier<'a>, - pub domain_description: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct DomainIdentifier<'a>(&'a str); - -impl<'a> DomainIdentifier<'a> { - pub fn new(domain_identifier: &'a str) -> Self { - Self(domain_identifier) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct DomainId(usize); - -impl utils::EntityId for DomainId { - #[inline] - fn get_id(&self) -> usize { - self.0 - } - - #[inline] - fn with_id(id: usize) -> Self { - Self(id) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct EdgeId(usize); +pub mod euclid_graph_prelude { + pub use hyperswitch_constraint_graph as cgraph; + pub use rustc_hash::{FxHashMap, FxHashSet}; -impl utils::EntityId for EdgeId { - #[inline] - fn get_id(&self) -> usize { - self.0 - } - - #[inline] - fn with_id(id: usize) -> Self { - Self(id) - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct Memoization(FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace>>>); - -impl Memoization { - pub fn new() -> Self { - Self(FxHashMap::default()) - } -} - -impl Default for Memoization { - #[inline] - fn default() -> Self { - Self::new() - } -} - -impl Deref for Memoization { - type Target = FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace>>>; - fn deref(&self) -> &Self::Target { - &self.0 - } -} -impl DerefMut for Memoization { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} -#[derive(Debug, Clone)] -pub struct Edge { - pub strength: Strength, - pub relation: Relation, - pub pred: NodeId, - pub succ: NodeId, + pub use crate::{ + dssa::graph::*, + frontend::dir::{enums::*, DirKey, DirKeyKind, DirValue}, + types::*, + }; } -#[derive(Debug)] -pub struct Node { - pub node_type: NodeType, - pub preds: Vec<EdgeId>, - pub succs: Vec<EdgeId>, - pub domain_ids: Vec<DomainId>, -} +impl cgraph::KeyNode for dir::DirKey {} -impl Node { - fn new(node_type: NodeType, domain_ids: Vec<DomainId>) -> Self { - Self { - node_type, - preds: Vec::new(), - succs: Vec::new(), - domain_ids, - } - } -} - -pub trait KgraphMetadata: ErasedSerialize + std::any::Any + Sync + Send + Debug {} -erased_serde::serialize_trait_object!(KgraphMetadata); - -impl<M> KgraphMetadata for M where M: ErasedSerialize + std::any::Any + Sync + Send + Debug {} - -#[derive(Debug)] -pub struct KnowledgeGraph<'a> { - domain: utils::DenseMap<DomainId, DomainInfo<'a>>, - nodes: utils::DenseMap<NodeId, Node>, - edges: utils::DenseMap<EdgeId, Edge>, - value_map: FxHashMap<NodeValue, NodeId>, - node_info: utils::DenseMap<NodeId, Option<&'static str>>, - node_metadata: utils::DenseMap<NodeId, Option<Arc<dyn KgraphMetadata>>>, -} - -pub struct KnowledgeGraphBuilder<'a> { - domain: utils::DenseMap<DomainId, DomainInfo<'a>>, - nodes: utils::DenseMap<NodeId, Node>, - edges: utils::DenseMap<EdgeId, Edge>, - domain_identifier_map: FxHashMap<DomainIdentifier<'a>, DomainId>, - value_map: FxHashMap<NodeValue, NodeId>, - edges_map: FxHashMap<(NodeId, NodeId), EdgeId>, - node_info: utils::DenseMap<NodeId, Option<&'static str>>, - node_metadata: utils::DenseMap<NodeId, Option<Arc<dyn KgraphMetadata>>>, -} +impl cgraph::ValueNode for dir::DirValue { + type Key = dir::DirKey; -impl<'a> Default for KnowledgeGraphBuilder<'a> { - #[inline] - fn default() -> Self { - Self::new() + fn get_key(&self) -> Self::Key { + Self::get_key(self) } } -#[derive(Debug, PartialEq, Eq)] -pub enum NodeType { - AllAggregator, - AnyAggregator, - InAggregator(FxHashSet<dir::DirValue>), - Value(NodeValue), -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)] -#[serde(tag = "type", content = "value", rename_all = "snake_case")] -pub enum NodeValue { - Key(dir::DirKey), - Value(dir::DirValue), -} - -impl From<dir::DirValue> for NodeValue { - fn from(value: dir::DirValue) -> Self { - Self::Value(value) - } -} - -impl From<dir::DirKey> for NodeValue { - fn from(key: dir::DirKey) -> Self { - Self::Key(key) - } -} - -#[derive(Debug, Clone, serde::Serialize)] -#[serde(tag = "type", content = "predecessor", rename_all = "snake_case")] -pub enum ValueTracePredecessor { - Mandatory(Box<Weak<AnalysisTrace>>), - OneOf(Vec<Weak<AnalysisTrace>>), -} - -#[derive(Debug, Clone, serde::Serialize)] -#[serde(tag = "type", content = "trace", rename_all = "snake_case")] -pub enum AnalysisTrace { - Value { - value: NodeValue, - relation: Relation, - predecessors: Option<ValueTracePredecessor>, - info: Option<&'static str>, - metadata: Option<Arc<dyn KgraphMetadata>>, - }, - - AllAggregation { - unsatisfied: Vec<Weak<AnalysisTrace>>, - info: Option<&'static str>, - metadata: Option<Arc<dyn KgraphMetadata>>, - }, - - AnyAggregation { - unsatisfied: Vec<Weak<AnalysisTrace>>, - info: Option<&'static str>, - metadata: Option<Arc<dyn KgraphMetadata>>, - }, - - InAggregation { - expected: Vec<dir::DirValue>, - found: Option<dir::DirValue>, - relation: Relation, - info: Option<&'static str>, - metadata: Option<Arc<dyn KgraphMetadata>>, - }, -} - #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "type", content = "details", rename_all = "snake_case")] -pub enum AnalysisError { - Graph(GraphError), +pub enum AnalysisError<V: cgraph::ValueNode> { + Graph(cgraph::GraphError<V>), AssertionTrace { - trace: Weak<AnalysisTrace>, + trace: Weak<cgraph::AnalysisTrace<V>>, metadata: Metadata, }, NegationTrace { - trace: Weak<AnalysisTrace>, + trace: Weak<cgraph::AnalysisTrace<V>>, metadata: Vec<Metadata>, }, } -impl AnalysisError { - fn assertion_from_graph_error(metadata: &Metadata, graph_error: GraphError) -> Self { +impl<V: cgraph::ValueNode> AnalysisError<V> { + fn assertion_from_graph_error(metadata: &Metadata, graph_error: cgraph::GraphError<V>) -> Self { match graph_error { - GraphError::AnalysisError(trace) => Self::AssertionTrace { + cgraph::GraphError::AnalysisError(trace) => Self::AssertionTrace { trace, metadata: metadata.clone(), }, @@ -275,9 +56,12 @@ impl AnalysisError { } } - fn negation_from_graph_error(metadata: Vec<&Metadata>, graph_error: GraphError) -> Self { + fn negation_from_graph_error( + metadata: Vec<&Metadata>, + graph_error: cgraph::GraphError<V>, + ) -> Self { match graph_error { - GraphError::AnalysisError(trace) => Self::NegationTrace { + cgraph::GraphError::AnalysisError(trace) => Self::NegationTrace { trace, metadata: metadata.iter().map(|m| (*m).clone()).collect(), }, @@ -287,56 +71,6 @@ impl AnalysisError { } } -#[derive(Debug, Clone, serde::Serialize, thiserror::Error)] -#[serde(tag = "type", content = "info", rename_all = "snake_case")] -pub enum GraphError { - #[error("An edge was not found in the graph")] - EdgeNotFound, - #[error("Attempted to create a conflicting edge between two nodes")] - ConflictingEdgeCreated, - #[error("Cycle detected in graph")] - CycleDetected, - #[error("Domain wasn't found in the Graph")] - DomainNotFound, - #[error("Malformed Graph: {reason}")] - MalformedGraph { reason: String }, - #[error("A node was not found in the graph")] - NodeNotFound, - #[error("A value node was not found: {0:#?}")] - ValueNodeNotFound(dir::DirValue), - #[error("No values provided for an 'in' aggregator node")] - NoInAggregatorValues, - #[error("Error during analysis: {0:#?}")] - AnalysisError(Weak<AnalysisTrace>), -} - -impl GraphError { - fn get_analysis_trace(self) -> Result<Weak<AnalysisTrace>, Self> { - match self { - Self::AnalysisError(trace) => Ok(trace), - _ => Err(self), - } - } -} - -impl PartialEq<dir::DirValue> for NodeValue { - fn eq(&self, other: &dir::DirValue) -> bool { - match self { - Self::Key(dir_key) => *dir_key == other.get_key(), - Self::Value(dir_value) if dir_value.get_key() == other.get_key() => { - if let (Some(left), Some(right)) = - (dir_value.get_num_value(), other.get_num_value()) - { - left.fits(&right) - } else { - dir::DirValue::check_equality(dir_value, other) - } - } - Self::Value(_) => false, - } - } -} - pub struct AnalysisContext { keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>>, } @@ -355,33 +89,6 @@ impl AnalysisContext { Self { keywise_values } } - fn check_presence(&self, value: &NodeValue, weak: bool) -> bool { - match value { - NodeValue::Key(k) => self.keywise_values.contains_key(k) || weak, - NodeValue::Value(val) => { - let key = val.get_key(); - let value_set = if let Some(set) = self.keywise_values.get(&key) { - set - } else { - return weak; - }; - - match key.kind.get_type() { - DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => { - value_set.contains(val) - } - DataType::Number => val.get_num_value().map_or(false, |num_val| { - value_set.iter().any(|ctx_val| { - ctx_val - .get_num_value() - .map_or(false, |ctx_num_val| num_val.fits(&ctx_num_val)) - }) - }), - } - } - } - } - pub fn insert(&mut self, value: dir::DirValue) { self.keywise_values .entry(value.get_key()) @@ -400,477 +107,153 @@ impl AnalysisContext { } } -impl<'a> KnowledgeGraphBuilder<'a> { - pub fn new() -> Self { - Self { - domain: utils::DenseMap::new(), - nodes: utils::DenseMap::new(), - edges: utils::DenseMap::new(), - domain_identifier_map: FxHashMap::default(), - value_map: FxHashMap::default(), - edges_map: FxHashMap::default(), - node_info: utils::DenseMap::new(), - node_metadata: utils::DenseMap::new(), - } - } - - pub fn build(self) -> KnowledgeGraph<'a> { - KnowledgeGraph { - domain: self.domain, - nodes: self.nodes, - edges: self.edges, - value_map: self.value_map, - node_info: self.node_info, - node_metadata: self.node_metadata, - } - } - - pub fn make_domain( - &mut self, - domain_identifier: DomainIdentifier<'a>, - domain_description: String, - ) -> Result<DomainId, GraphError> { - Ok(self - .domain_identifier_map - .clone() - .get(&domain_identifier) - .map_or_else( - || { - let domain_id = self.domain.push(DomainInfo { - domain_identifier: domain_identifier.clone(), - domain_description, - }); - self.domain_identifier_map - .insert(domain_identifier.clone(), domain_id); - domain_id - }, - |domain_id| *domain_id, - )) - } - - pub fn make_value_node<M: KgraphMetadata>( - &mut self, - value: NodeValue, - info: Option<&'static str>, - domain_identifiers: Vec<DomainIdentifier<'_>>, - metadata: Option<M>, - ) -> Result<NodeId, GraphError> { - match self.value_map.get(&value).copied() { - Some(node_id) => Ok(node_id), - None => { - let mut domain_ids: Vec<DomainId> = Vec::new(); - domain_identifiers - .iter() - .try_for_each(|ident| { - self.domain_identifier_map - .get(ident) - .map(|id| domain_ids.push(*id)) - }) - .ok_or(GraphError::DomainNotFound)?; - - let node_id = self - .nodes - .push(Node::new(NodeType::Value(value.clone()), domain_ids)); - let _node_info_id = self.node_info.push(info); - - let _node_metadata_id = self - .node_metadata - .push(metadata.map(|meta| -> Arc<dyn KgraphMetadata> { Arc::new(meta) })); - - self.value_map.insert(value, node_id); - Ok(node_id) - } - } - } - - pub fn make_edge( - &mut self, - pred_id: NodeId, - succ_id: NodeId, - strength: Strength, - relation: Relation, - ) -> Result<EdgeId, GraphError> { - self.ensure_node_exists(pred_id)?; - self.ensure_node_exists(succ_id)?; - self.edges_map - .get(&(pred_id, succ_id)) - .copied() - .and_then(|edge_id| self.edges.get(edge_id).cloned().map(|edge| (edge_id, edge))) - .map_or_else( - || { - let edge_id = self.edges.push(Edge { - strength, - relation, - pred: pred_id, - succ: succ_id, - }); - self.edges_map.insert((pred_id, succ_id), edge_id); - - let pred = self - .nodes - .get_mut(pred_id) - .ok_or(GraphError::NodeNotFound)?; - pred.succs.push(edge_id); - - let succ = self - .nodes - .get_mut(succ_id) - .ok_or(GraphError::NodeNotFound)?; - succ.preds.push(edge_id); - - Ok(edge_id) - }, - |(edge_id, edge)| { - if edge.strength == strength && edge.relation == relation { - Ok(edge_id) - } else { - Err(GraphError::ConflictingEdgeCreated) - } - }, - ) - } - - pub fn make_all_aggregator<M: KgraphMetadata>( - &mut self, - nodes: &[(NodeId, Relation, Strength)], - info: Option<&'static str>, - metadata: Option<M>, - domain: Vec<DomainIdentifier<'_>>, - ) -> Result<NodeId, GraphError> { - nodes - .iter() - .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; +impl cgraph::CheckingContext for AnalysisContext { + type Value = dir::DirValue; - let mut domain_ids: Vec<DomainId> = Vec::new(); - domain - .iter() - .try_for_each(|ident| { - self.domain_identifier_map - .get(ident) - .map(|id| domain_ids.push(*id)) - }) - .ok_or(GraphError::DomainNotFound)?; - - let aggregator_id = self - .nodes - .push(Node::new(NodeType::AllAggregator, domain_ids)); - let _aggregator_info_id = self.node_info.push(info); - - let _node_metadata_id = self - .node_metadata - .push(metadata.map(|meta| -> Arc<dyn KgraphMetadata> { Arc::new(meta) })); + fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self + where + L: Into<Self::Value>, + { + let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> = + FxHashMap::default(); - for (node_id, relation, strength) in nodes { - self.make_edge(*node_id, aggregator_id, *strength, *relation)?; + for dir_val in vals.into_iter().map(L::into) { + let key = dir_val.get_key(); + let set = keywise_values.entry(key).or_default(); + set.insert(dir_val); } - Ok(aggregator_id) + Self { keywise_values } } - pub fn make_any_aggregator<M: KgraphMetadata>( - &mut self, - nodes: &[(NodeId, Relation)], - info: Option<&'static str>, - metadata: Option<M>, - domain: Vec<DomainIdentifier<'_>>, - ) -> Result<NodeId, GraphError> { - nodes - .iter() - .try_for_each(|(node_id, _)| self.ensure_node_exists(*node_id))?; - - let mut domain_ids: Vec<DomainId> = Vec::new(); - domain - .iter() - .try_for_each(|ident| { - self.domain_identifier_map - .get(ident) - .map(|id| domain_ids.push(*id)) - }) - .ok_or(GraphError::DomainNotFound)?; - - let aggregator_id = self - .nodes - .push(Node::new(NodeType::AnyAggregator, domain_ids)); - let _aggregator_info_id = self.node_info.push(info); - - let _node_metadata_id = self - .node_metadata - .push(metadata.map(|meta| -> Arc<dyn KgraphMetadata> { Arc::new(meta) })); - - for (node_id, relation) in nodes { - self.make_edge(*node_id, aggregator_id, Strength::Strong, *relation)?; - } + fn check_presence( + &self, + value: &cgraph::NodeValue<dir::DirValue>, + strength: cgraph::Strength, + ) -> bool { + match value { + cgraph::NodeValue::Key(k) => { + self.keywise_values.contains_key(k) || matches!(strength, cgraph::Strength::Weak) + } - Ok(aggregator_id) - } + cgraph::NodeValue::Value(val) => { + let key = val.get_key(); + let value_set = if let Some(set) = self.keywise_values.get(&key) { + set + } else { + return matches!(strength, cgraph::Strength::Weak); + }; - pub fn make_in_aggregator<M: KgraphMetadata>( - &mut self, - values: Vec<dir::DirValue>, - info: Option<&'static str>, - metadata: Option<M>, - domain: Vec<DomainIdentifier<'_>>, - ) -> Result<NodeId, GraphError> { - let key = values - .first() - .ok_or(GraphError::NoInAggregatorValues)? - .get_key(); - - for val in &values { - if val.get_key() != key { - Err(GraphError::MalformedGraph { - reason: "Values for 'In' aggregator not of same key".to_string(), - })?; + match key.kind.get_type() { + DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => { + value_set.contains(val) + } + DataType::Number => val.get_num_value().map_or(false, |num_val| { + value_set.iter().any(|ctx_val| { + ctx_val + .get_num_value() + .map_or(false, |ctx_num_val| num_val.fits(&ctx_num_val)) + }) + }), + } } } - - let mut domain_ids: Vec<DomainId> = Vec::new(); - domain - .iter() - .try_for_each(|ident| { - self.domain_identifier_map - .get(ident) - .map(|id| domain_ids.push(*id)) - }) - .ok_or(GraphError::DomainNotFound)?; - - let node_id = self.nodes.push(Node::new( - NodeType::InAggregator(FxHashSet::from_iter(values)), - domain_ids, - )); - let _aggregator_info_id = self.node_info.push(info); - - let _node_metadata_id = self - .node_metadata - .push(metadata.map(|meta| -> Arc<dyn KgraphMetadata> { Arc::new(meta) })); - - Ok(node_id) } - fn ensure_node_exists(&self, id: NodeId) -> Result<(), GraphError> { - if self.nodes.contains_key(id) { - Ok(()) - } else { - Err(GraphError::NodeNotFound) - } + fn get_values_by_key( + &self, + key: &<Self::Value as cgraph::ValueNode>::Key, + ) -> Option<Vec<Self::Value>> { + self.keywise_values + .get(key) + .map(|set| set.iter().cloned().collect()) } } -impl<'a> KnowledgeGraph<'a> { - fn check_node( +pub trait CgraphExt { + fn key_analysis( &self, + key: dir::DirKey, ctx: &AnalysisContext, - node_id: NodeId, - relation: Relation, - strength: Strength, - memo: &mut Memoization, - ) -> Result<(), GraphError> { - let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; - if let Some(already_memo) = memo.get(&(node_id, relation, strength)) { - already_memo - .clone() - .map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err))) - } else { - match &node.node_type { - NodeType::AllAggregator => { - let mut unsatisfied = Vec::<Weak<AnalysisTrace>>::new(); - - for edge_id in node.preds.iter().copied() { - let edge = self.edges.get(edge_id).ok_or(GraphError::EdgeNotFound)?; - - if let Err(e) = - self.check_node(ctx, edge.pred, edge.relation, edge.strength, memo) - { - unsatisfied.push(e.get_analysis_trace()?); - } - } - - if !unsatisfied.is_empty() { - let err = Arc::new(AnalysisTrace::AllAggregation { - unsatisfied, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err))) - } else { - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } - } - - NodeType::AnyAggregator => { - let mut unsatisfied = Vec::<Weak<AnalysisTrace>>::new(); - let mut matched_one = false; - - for edge_id in node.preds.iter().copied() { - let edge = self.edges.get(edge_id).ok_or(GraphError::EdgeNotFound)?; - - if let Err(e) = - self.check_node(ctx, edge.pred, edge.relation, edge.strength, memo) - { - unsatisfied.push(e.get_analysis_trace()?); - } else { - matched_one = true; - } - } - - if matched_one || node.preds.is_empty() { - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } else { - let err = Arc::new(AnalysisTrace::AnyAggregation { - unsatisfied: unsatisfied.clone(), - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err))) - } - } + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>>; - NodeType::InAggregator(expected) => { - let the_key = expected - .iter() - .next() - .ok_or_else(|| GraphError::MalformedGraph { - reason: - "An OnlyIn aggregator node must have at least one expected value" - .to_string(), - })? - .get_key(); - - let ctx_vals = if let Some(vals) = ctx.keywise_values.get(&the_key) { - vals - } else { - return if let Strength::Weak = strength { - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } else { - let err = Arc::new(AnalysisTrace::InAggregation { - expected: expected.iter().cloned().collect(), - found: None, - relation, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err))) - }; - }; - - let relation_bool: bool = relation.into(); - for ctx_value in ctx_vals { - if expected.contains(ctx_value) != relation_bool { - let err = Arc::new(AnalysisTrace::InAggregation { - expected: expected.iter().cloned().collect(), - found: Some(ctx_value.clone()), - relation, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; - } - } + fn value_analysis( + &self, + val: dir::DirValue, + ctx: &AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>>; - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } + fn check_value_validity( + &self, + val: dir::DirValue, + analysis_ctx: &AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<bool, cgraph::GraphError<dir::DirValue>>; - NodeType::Value(val) => { - let in_context = ctx.check_presence(val, matches!(strength, Strength::Weak)); - let relation_bool: bool = relation.into(); - - if in_context != relation_bool { - let err = Arc::new(AnalysisTrace::Value { - value: val.clone(), - relation, - predecessors: None, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; - } + fn key_value_analysis( + &self, + val: dir::DirValue, + ctx: &AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>>; - if !relation_bool { - memo.insert((node_id, relation, strength), Ok(())); - return Ok(()); - } + fn assertion_analysis( + &self, + positive_ctx: &[(&dir::DirValue, &Metadata)], + analysis_ctx: &AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>>; - let mut errors = Vec::<Weak<AnalysisTrace>>::new(); - let mut matched_one = false; - - for edge_id in node.preds.iter().copied() { - let edge = self.edges.get(edge_id).ok_or(GraphError::EdgeNotFound)?; - let result = - self.check_node(ctx, edge.pred, edge.relation, edge.strength, memo); - - match (edge.strength, result) { - (Strength::Strong, Err(trace)) => { - let err = Arc::new(AnalysisTrace::Value { - value: val.clone(), - relation, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - predecessors: Some(ValueTracePredecessor::Mandatory(Box::new( - trace.get_analysis_trace()?, - ))), - }); - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; - } - - (Strength::Strong, Ok(_)) => { - matched_one = true; - } - - (Strength::Normal | Strength::Weak, Err(trace)) => { - errors.push(trace.get_analysis_trace()?); - } - - (Strength::Normal | Strength::Weak, Ok(_)) => { - matched_one = true; - } - } - } + fn negation_analysis( + &self, + negative_ctx: &[(&[dir::DirValue], &Metadata)], + analysis_ctx: &mut AnalysisContext, + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>>; - if matched_one || node.preds.is_empty() { - memo.insert((node_id, relation, strength), Ok(())); - Ok(()) - } else { - let err = Arc::new(AnalysisTrace::Value { - value: val.clone(), - relation, - info: self.node_info.get(node_id).cloned().flatten(), - metadata: self.node_metadata.get(node_id).cloned().flatten(), - predecessors: Some(ValueTracePredecessor::OneOf(errors.clone())), - }); - - memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); - Err(GraphError::AnalysisError(Arc::downgrade(&err))) - } - } - } - } - } + fn perform_context_analysis( + &self, + ctx: &types::ConjunctiveContext<'_>, + memo: &mut cgraph::Memoization<dir::DirValue>, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>>; +} +impl CgraphExt for cgraph::ConstraintGraph<'_, dir::DirValue> { fn key_analysis( &self, key: dir::DirKey, ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), GraphError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.value_map - .get(&NodeValue::Key(key)) + .get(&cgraph::NodeValue::Key(key)) .map_or(Ok(()), |node_id| { - self.check_node(ctx, *node_id, Relation::Positive, Strength::Strong, memo) + self.check_node( + ctx, + *node_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + memo, + cycle_map, + domains, + ) }) } @@ -878,22 +261,34 @@ impl<'a> KnowledgeGraph<'a> { &self, val: dir::DirValue, ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), GraphError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>> { self.value_map - .get(&NodeValue::Value(val)) + .get(&cgraph::NodeValue::Value(val)) .map_or(Ok(()), |node_id| { - self.check_node(ctx, *node_id, Relation::Positive, Strength::Strong, memo) + self.check_node( + ctx, + *node_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + memo, + cycle_map, + domains, + ) }) } - pub fn check_value_validity( + fn check_value_validity( &self, val: dir::DirValue, analysis_ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<bool, GraphError> { - let maybe_node_id = self.value_map.get(&NodeValue::Value(val)); + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<bool, cgraph::GraphError<dir::DirValue>> { + let maybe_node_id = self.value_map.get(&cgraph::NodeValue::Value(val)); let node_id = if let Some(nid) = maybe_node_id { nid @@ -904,9 +299,11 @@ impl<'a> KnowledgeGraph<'a> { let result = self.check_node( analysis_ctx, *node_id, - Relation::Positive, - Strength::Weak, + cgraph::Relation::Positive, + cgraph::Strength::Weak, memo, + cycle_map, + domains, ); match result { @@ -918,24 +315,28 @@ impl<'a> KnowledgeGraph<'a> { } } - pub fn key_value_analysis( + fn key_value_analysis( &self, val: dir::DirValue, ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), GraphError> { - self.key_analysis(val.get_key(), ctx, memo) - .and_then(|_| self.value_analysis(val, ctx, memo)) + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), cgraph::GraphError<dir::DirValue>> { + self.key_analysis(val.get_key(), ctx, memo, cycle_map, domains) + .and_then(|_| self.value_analysis(val, ctx, memo, cycle_map, domains)) } fn assertion_analysis( &self, positive_ctx: &[(&dir::DirValue, &Metadata)], analysis_ctx: &AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), AnalysisError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>> { positive_ctx.iter().try_for_each(|(value, metadata)| { - self.key_value_analysis((*value).clone(), analysis_ctx, memo) + self.key_value_analysis((*value).clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(metadata, e)) }) } @@ -944,8 +345,10 @@ impl<'a> KnowledgeGraph<'a> { &self, negative_ctx: &[(&[dir::DirValue], &Metadata)], analysis_ctx: &mut AnalysisContext, - memo: &mut Memoization, - ) -> Result<(), AnalysisError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + cycle_map: &mut cgraph::CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>> { let mut keywise_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> = FxHashMap::default(); let mut keywise_negation: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> = FxHashMap::default(); @@ -974,7 +377,7 @@ impl<'a> KnowledgeGraph<'a> { let all_metadata = keywise_metadata.remove(&key).unwrap_or_default(); let first_metadata = all_metadata.first().cloned().cloned().unwrap_or_default(); - self.key_analysis(key.clone(), analysis_ctx, memo) + self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?; let mut value_set = if let Some(set) = key.kind.get_value_set() { @@ -987,7 +390,7 @@ impl<'a> KnowledgeGraph<'a> { for value in value_set { analysis_ctx.insert(value.clone()); - self.value_analysis(value.clone(), analysis_ctx, memo) + self.value_analysis(value.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| { AnalysisError::negation_from_graph_error(all_metadata.clone(), e) })?; @@ -998,11 +401,12 @@ impl<'a> KnowledgeGraph<'a> { Ok(()) } - pub fn perform_context_analysis( + fn perform_context_analysis( &self, ctx: &types::ConjunctiveContext<'_>, - memo: &mut Memoization, - ) -> Result<(), AnalysisError> { + memo: &mut cgraph::Memoization<dir::DirValue>, + domains: Option<&[&str]>, + ) -> Result<(), AnalysisError<dir::DirValue>> { let mut analysis_ctx = AnalysisContext::from_dir_values( ctx.iter() .filter_map(|ctx_val| ctx_val.value.get_assertion().cloned()), @@ -1017,7 +421,13 @@ impl<'a> KnowledgeGraph<'a> { .map(|val| (val, ctx_val.metadata)) }) .collect::<Vec<_>>(); - self.assertion_analysis(&positive_ctx, &analysis_ctx, memo)?; + self.assertion_analysis( + &positive_ctx, + &analysis_ctx, + memo, + &mut cgraph::CycleCheck::new(), + domains, + )?; let negative_ctx = ctx .iter() @@ -1028,127 +438,38 @@ impl<'a> KnowledgeGraph<'a> { .map(|vals| (vals, ctx_val.metadata)) }) .collect::<Vec<_>>(); - self.negation_analysis(&negative_ctx, &mut analysis_ctx, memo)?; + self.negation_analysis( + &negative_ctx, + &mut analysis_ctx, + memo, + &mut cgraph::CycleCheck::new(), + domains, + )?; Ok(()) } - - pub fn combine<'b>(g1: &'b Self, g2: &'b Self) -> Result<Self, GraphError> { - let mut node_builder = KnowledgeGraphBuilder::new(); - let mut g1_old2new_id = utils::DenseMap::<NodeId, NodeId>::new(); - let mut g2_old2new_id = utils::DenseMap::<NodeId, NodeId>::new(); - let mut g1_old2new_domain_id = utils::DenseMap::<DomainId, DomainId>::new(); - let mut g2_old2new_domain_id = utils::DenseMap::<DomainId, DomainId>::new(); - - let add_domain = |node_builder: &mut KnowledgeGraphBuilder<'a>, - domain: DomainInfo<'a>| - -> Result<DomainId, GraphError> { - node_builder.make_domain(domain.domain_identifier, domain.domain_description) - }; - - let add_node = |node_builder: &mut KnowledgeGraphBuilder<'a>, - node: &Node, - domains: Vec<DomainIdentifier<'_>>| - -> Result<NodeId, GraphError> { - match &node.node_type { - NodeType::Value(node_value) => { - node_builder.make_value_node(node_value.clone(), None, domains, None::<()>) - } - - NodeType::AllAggregator => { - Ok(node_builder.make_all_aggregator(&[], None, None::<()>, domains)?) - } - - NodeType::AnyAggregator => { - Ok(node_builder.make_any_aggregator(&[], None, None::<()>, Vec::new())?) - } - - NodeType::InAggregator(expected) => Ok(node_builder.make_in_aggregator( - expected.iter().cloned().collect(), - None, - None::<()>, - Vec::new(), - )?), - } - }; - - for (_old_domain_id, domain) in g1.domain.iter() { - let new_domain_id = add_domain(&mut node_builder, domain.clone())?; - g1_old2new_domain_id.push(new_domain_id); - } - - for (_old_domain_id, domain) in g2.domain.iter() { - let new_domain_id = add_domain(&mut node_builder, domain.clone())?; - g2_old2new_domain_id.push(new_domain_id); - } - - for (_old_node_id, node) in g1.nodes.iter() { - let mut domain_identifiers: Vec<DomainIdentifier<'_>> = Vec::new(); - for domain_id in &node.domain_ids { - match g1.domain.get(*domain_id) { - Some(domain) => domain_identifiers.push(domain.domain_identifier.clone()), - None => return Err(GraphError::DomainNotFound), - } - } - let new_node_id = add_node(&mut node_builder, node, domain_identifiers.clone())?; - g1_old2new_id.push(new_node_id); - } - - for (_old_node_id, node) in g2.nodes.iter() { - let mut domain_identifiers: Vec<DomainIdentifier<'_>> = Vec::new(); - for domain_id in &node.domain_ids { - match g2.domain.get(*domain_id) { - Some(domain) => domain_identifiers.push(domain.domain_identifier.clone()), - None => return Err(GraphError::DomainNotFound), - } - } - let new_node_id = add_node(&mut node_builder, node, domain_identifiers.clone())?; - g2_old2new_id.push(new_node_id); - } - - for edge in g1.edges.values() { - let new_pred_id = g1_old2new_id - .get(edge.pred) - .ok_or(GraphError::NodeNotFound)?; - let new_succ_id = g1_old2new_id - .get(edge.succ) - .ok_or(GraphError::NodeNotFound)?; - - node_builder.make_edge(*new_pred_id, *new_succ_id, edge.strength, edge.relation)?; - } - - for edge in g2.edges.values() { - let new_pred_id = g2_old2new_id - .get(edge.pred) - .ok_or(GraphError::NodeNotFound)?; - let new_succ_id = g2_old2new_id - .get(edge.succ) - .ok_or(GraphError::NodeNotFound)?; - - node_builder.make_edge(*new_pred_id, *new_succ_id, edge.strength, edge.relation)?; - } - - Ok(node_builder.build()) - } } #[cfg(test)] mod test { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use std::ops::Deref; + use euclid_macros::knowledge; + use hyperswitch_constraint_graph::CycleCheck; use super::*; use crate::{dirval, frontend::dir::enums}; #[test] fn test_strong_positive_relation_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) ->> CaptureMethod(Automatic); PaymentMethod(not Wallet) & PaymentMethod(not PayLater) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1156,6 +477,8 @@ mod test { dirval!(PaymentMethod = Card), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1163,15 +486,17 @@ mod test { #[test] fn test_strong_positive_relation_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) ->> CaptureMethod(Automatic); PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([dirval!(CaptureMethod = Automatic)]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1179,11 +504,11 @@ mod test { #[test] fn test_strong_negative_relation_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1191,6 +516,8 @@ mod test { dirval!(PaymentMethod = Card), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1198,11 +525,11 @@ mod test { #[test] fn test_strong_negative_relation_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1210,6 +537,8 @@ mod test { dirval!(PaymentMethod = Wallet), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1217,11 +546,11 @@ mod test { #[test] fn test_normal_one_of_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) -> CaptureMethod(Automatic); PaymentMethod(Wallet) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1229,12 +558,14 @@ mod test { dirval!(PaymentMethod = PayLater), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(matches!( *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected Arc"), - AnalysisTrace::Value { - predecessors: Some(ValueTracePredecessor::OneOf(_)), + cgraph::AnalysisTrace::Value { + predecessors: Some(cgraph::error::ValueTracePredecessor::OneOf(_)), .. } )); @@ -1242,10 +573,10 @@ mod test { #[test] fn test_all_aggregator_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1253,6 +584,8 @@ mod test { dirval!(CaptureMethod = Automatic), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1260,10 +593,10 @@ mod test { #[test] fn test_all_aggregator_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1271,6 +604,8 @@ mod test { dirval!(PaymentMethod = PayLater), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1278,10 +613,10 @@ mod test { #[test] fn test_all_aggregator_mandatory_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(Card) & PaymentMethod(not Wallet) ->> CaptureMethod(Automatic); }; - let mut memo = Memoization::new(); + let mut memo = cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1289,13 +624,15 @@ mod test { dirval!(PaymentMethod = PayLater), ]), &mut memo, + &mut CycleCheck::new(), + None, ); assert!(matches!( *Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected Arc"), - AnalysisTrace::Value { - predecessors: Some(ValueTracePredecessor::Mandatory(_)), + cgraph::AnalysisTrace::Value { + predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(_)), .. } )); @@ -1303,10 +640,10 @@ mod test { #[test] fn test_in_aggregator_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1315,6 +652,8 @@ mod test { dirval!(PaymentMethod = Wallet), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1322,10 +661,10 @@ mod test { #[test] fn test_in_aggregator_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1335,6 +674,8 @@ mod test { dirval!(PaymentMethod = PayLater), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1342,10 +683,10 @@ mod test { #[test] fn test_not_in_aggregator_success() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1354,6 +695,8 @@ mod test { dirval!(PaymentMethod = BankRedirect), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -1361,10 +704,10 @@ mod test { #[test] fn test_not_in_aggregator_failure() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1374,6 +717,8 @@ mod test { dirval!(PaymentMethod = Card), ]), memo, + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -1381,10 +726,10 @@ mod test { #[test] fn test_in_aggregator_failure_trace() { - let graph = knowledge! {crate + let graph = knowledge! { PaymentMethod(in [Card, Wallet]) ->> CaptureMethod(Automatic); }; - let memo = &mut Memoization::new(); + let memo = &mut cgraph::Memoization::new(); let result = graph.key_value_analysis( dirval!(CaptureMethod = Automatic), &AnalysisContext::from_dir_values([ @@ -1394,10 +739,12 @@ mod test { dirval!(PaymentMethod = PayLater), ]), memo, + &mut CycleCheck::new(), + None, ); - if let AnalysisTrace::Value { - predecessors: Some(ValueTracePredecessor::Mandatory(agg_error)), + if let cgraph::AnalysisTrace::Value { + predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(agg_error)), .. } = Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap()) .expect("Expected arc") @@ -1405,7 +752,7 @@ mod test { { assert!(matches!( *Weak::upgrade(agg_error.deref()).expect("Expected Arc"), - AnalysisTrace::InAggregation { + cgraph::AnalysisTrace::InAggregation { found: Some(dir::DirValue::PaymentMethod(enums::PaymentMethod::PayLater)), .. } @@ -1416,43 +763,43 @@ mod test { } #[test] - fn _test_memoization_in_kgraph() { - let mut builder = KnowledgeGraphBuilder::new(); + fn test_memoization_in_kgraph() { + let mut builder = cgraph::ConstraintGraphBuilder::new(); let _node_1 = builder.make_value_node( - NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), None, - Vec::new(), None::<()>, ); let _node_2 = builder.make_value_node( - NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)), + cgraph::NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)), None, - Vec::new(), None::<()>, ); let _node_3 = builder.make_value_node( - NodeValue::Value(dir::DirValue::BusinessCountry( + cgraph::NodeValue::Value(dir::DirValue::BusinessCountry( enums::BusinessCountry::UnitedStatesOfAmerica, )), None, - Vec::new(), None::<()>, ); - let mut memo = Memoization::new(); + let mut memo = cgraph::Memoization::new(); + let mut cycle_map = CycleCheck::new(); let _edge_1 = builder .make_edge( - _node_1.expect("node1 constructtion failed"), - _node_2.clone().expect("node2 construction failed"), - Strength::Strong, - Relation::Positive, + _node_1, + _node_2, + cgraph::Strength::Strong, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, ) .expect("Failed to make an edge"); let _edge_2 = builder .make_edge( - _node_2.expect("node2 construction failed"), - _node_3.clone().expect("node3 construction failed"), - Strength::Strong, - Relation::Positive, + _node_2, + _node_3, + cgraph::Strength::Strong, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, ) .expect("Failed to an edge"); let graph = builder.build(); @@ -1464,15 +811,263 @@ mod test { dirval!(BusinessCountry = UnitedStatesOfAmerica), ]), &mut memo, + &mut cycle_map, + None, ); let _answer = memo - .0 .get(&( - _node_3.expect("node3 construction failed"), - Relation::Positive, - Strength::Strong, + _node_3, + cgraph::Relation::Positive, + cgraph::Strength::Strong, )) .expect("Memoization not workng"); matches!(_answer, Ok(())); } + + #[test] + fn test_cycle_resolution_in_graph() { + let mut builder = cgraph::ConstraintGraphBuilder::new(); + let _node_1 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), + None, + None::<()>, + ); + let _node_2 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), + None, + None::<()>, + ); + let mut memo = cgraph::Memoization::new(); + let mut cycle_map = cgraph::CycleCheck::new(); + let _edge_1 = builder + .make_edge( + _node_1, + _node_2, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_2 = builder + .make_edge( + _node_2, + _node_1, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to an edge"); + let graph = builder.build(); + let _result = graph.key_value_analysis( + dirval!(PaymentMethod = Wallet), + &AnalysisContext::from_dir_values([ + dirval!(PaymentMethod = Wallet), + dirval!(PaymentMethod = Card), + ]), + &mut memo, + &mut cycle_map, + None, + ); + + assert!(_result.is_ok()); + } + + #[test] + fn test_cycle_resolution_in_graph1() { + let mut builder = cgraph::ConstraintGraphBuilder::new(); + let _node_1 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( + enums::CaptureMethod::Automatic, + )), + None, + None::<()>, + ); + + let _node_2 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), + None, + None::<()>, + ); + let _node_3 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), + None, + None::<()>, + ); + let mut memo = cgraph::Memoization::new(); + let mut cycle_map = cgraph::CycleCheck::new(); + + let _edge_1 = builder + .make_edge( + _node_1, + _node_2, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_2 = builder + .make_edge( + _node_1, + _node_3, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_3 = builder + .make_edge( + _node_2, + _node_1, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_4 = builder + .make_edge( + _node_3, + _node_1, + cgraph::Strength::Strong, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + + let graph = builder.build(); + let _result = graph.key_value_analysis( + dirval!(CaptureMethod = Automatic), + &AnalysisContext::from_dir_values([ + dirval!(PaymentMethod = Card), + dirval!(PaymentMethod = Wallet), + dirval!(CaptureMethod = Automatic), + ]), + &mut memo, + &mut cycle_map, + None, + ); + + assert!(_result.is_ok()); + } + + #[test] + fn test_cycle_resolution_in_graph2() { + let mut builder = cgraph::ConstraintGraphBuilder::new(); + let _node_0 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::BillingCountry( + enums::BillingCountry::Afghanistan, + )), + None, + None::<()>, + ); + + let _node_1 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::CaptureMethod( + enums::CaptureMethod::Automatic, + )), + None, + None::<()>, + ); + + let _node_2 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)), + None, + None::<()>, + ); + let _node_3 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)), + None, + None::<()>, + ); + + let _node_4 = builder.make_value_node( + cgraph::NodeValue::Value(dir::DirValue::PaymentCurrency(enums::PaymentCurrency::USD)), + None, + None::<()>, + ); + + let mut memo = cgraph::Memoization::new(); + let mut cycle_map = cgraph::CycleCheck::new(); + + let _edge_1 = builder + .make_edge( + _node_0, + _node_1, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_2 = builder + .make_edge( + _node_1, + _node_2, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_3 = builder + .make_edge( + _node_1, + _node_3, + cgraph::Strength::Weak, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_4 = builder + .make_edge( + _node_3, + _node_4, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_5 = builder + .make_edge( + _node_2, + _node_4, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + + let _edge_6 = builder + .make_edge( + _node_4, + _node_1, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + let _edge_7 = builder + .make_edge( + _node_4, + _node_0, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, + ) + .expect("Failed to make an edge"); + + let graph = builder.build(); + let _result = graph.key_value_analysis( + dirval!(BillingCountry = Afghanistan), + &AnalysisContext::from_dir_values([ + dirval!(PaymentCurrency = USD), + dirval!(PaymentMethod = Card), + dirval!(PaymentMethod = Wallet), + dirval!(CaptureMethod = Automatic), + dirval!(BillingCountry = Afghanistan), + ]), + &mut memo, + &mut cycle_map, + None, + ); + + assert!(_result.is_ok()); + } } diff --git a/crates/euclid/src/dssa/truth.rs b/crates/euclid/src/dssa/truth.rs index 17e6e728e68..388180eed5b 100644 --- a/crates/euclid/src/dssa/truth.rs +++ b/crates/euclid/src/dssa/truth.rs @@ -1,29 +1,30 @@ use euclid_macros::knowledge; use once_cell::sync::Lazy; -use crate::dssa::graph; +use crate::{dssa::graph::euclid_graph_prelude, frontend::dir}; -pub static ANALYSIS_GRAPH: Lazy<graph::KnowledgeGraph<'_>> = Lazy::new(|| { - knowledge! {crate - // Payment Method should be `Card` for a CardType to be present - PaymentMethod(Card) ->> CardType(any); +pub static ANALYSIS_GRAPH: Lazy<hyperswitch_constraint_graph::ConstraintGraph<'_, dir::DirValue>> = + Lazy::new(|| { + knowledge! { + // Payment Method should be `Card` for a CardType to be present + PaymentMethod(Card) ->> CardType(any); - // Payment Method should be `PayLater` for a PayLaterType to be present - PaymentMethod(PayLater) ->> PayLaterType(any); + // Payment Method should be `PayLater` for a PayLaterType to be present + PaymentMethod(PayLater) ->> PayLaterType(any); - // Payment Method should be `Wallet` for a WalletType to be present - PaymentMethod(Wallet) ->> WalletType(any); + // Payment Method should be `Wallet` for a WalletType to be present + PaymentMethod(Wallet) ->> WalletType(any); - // Payment Method should be `BankRedirect` for a BankRedirectType to - // be present - PaymentMethod(BankRedirect) ->> BankRedirectType(any); + // Payment Method should be `BankRedirect` for a BankRedirectType to + // be present + PaymentMethod(BankRedirect) ->> BankRedirectType(any); - // Payment Method should be `BankTransfer` for a BankTransferType to - // be present - PaymentMethod(BankTransfer) ->> BankTransferType(any); + // Payment Method should be `BankTransfer` for a BankTransferType to + // be present + PaymentMethod(BankTransfer) ->> BankTransferType(any); - // Payment Method should be `GiftCard` for a GiftCardType to - // be present - PaymentMethod(GiftCard) ->> GiftCardType(any); - } -}); + // Payment Method should be `GiftCard` for a GiftCardType to + // be present + PaymentMethod(GiftCard) ->> GiftCardType(any); + } + }); diff --git a/crates/euclid/src/dssa/types.rs b/crates/euclid/src/dssa/types.rs index 4070e0825ef..df54de2dd99 100644 --- a/crates/euclid/src/dssa/types.rs +++ b/crates/euclid/src/dssa/types.rs @@ -140,7 +140,10 @@ pub enum AnalysisErrorType { negation_metadata: Metadata, }, #[error("Graph analysis error: {0:#?}")] - GraphAnalysis(graph::AnalysisError, graph::Memoization), + GraphAnalysis( + graph::AnalysisError<dir::DirValue>, + hyperswitch_constraint_graph::Memoization<dir::DirValue>, + ), #[error("State machine error")] StateMachine(dssa::state_machine::StateMachineError), #[error("Unsupported program key '{0}'")] diff --git a/crates/euclid/src/lib.rs b/crates/euclid/src/lib.rs index d64297437ae..261b3dc02d6 100644 --- a/crates/euclid/src/lib.rs +++ b/crates/euclid/src/lib.rs @@ -4,4 +4,3 @@ pub mod dssa; pub mod enums; pub mod frontend; pub mod types; -pub mod utils; diff --git a/crates/euclid/src/utils.rs b/crates/euclid/src/utils.rs deleted file mode 100644 index e8cb7901f0d..00000000000 --- a/crates/euclid/src/utils.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod dense_map; - -pub use dense_map::{DenseMap, EntityId}; diff --git a/crates/euclid_macros/src/inner/knowledge.rs b/crates/euclid_macros/src/inner/knowledge.rs index 9f33a6871c5..a9c453b42c6 100644 --- a/crates/euclid_macros/src/inner/knowledge.rs +++ b/crates/euclid_macros/src/inner/knowledge.rs @@ -329,19 +329,17 @@ impl ToString for Scope { #[derive(Clone)] struct Program { rules: Vec<Rc<Rule>>, - scope: Scope, } impl Parse for Program { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { - let scope: Scope = input.parse()?; let mut rules: Vec<Rc<Rule>> = Vec::new(); while !input.is_empty() { rules.push(Rc::new(input.parse::<Rule>()?)); } - Ok(Self { rules, scope }) + Ok(Self { rules }) } } @@ -502,12 +500,12 @@ impl GenContext { let key = format_ident!("{}", &atom.key); let the_value = match &atom.value { ValueType::Any => quote! { - NodeValue::Key(DirKey::new(DirKeyKind::#key,None)) + cgraph::NodeValue::Key(DirKey::new(DirKeyKind::#key,None)) }, ValueType::EnumVariant(variant) => { let variant = format_ident!("{}", variant); quote! { - NodeValue::Value(DirValue::#key(#key::#variant)) + cgraph::NodeValue::Value(DirValue::#key(#key::#variant)) } } ValueType::Number { number, comparison } => { @@ -530,7 +528,7 @@ impl GenContext { }; quote! { - NodeValue::Value(DirValue::#key(NumValue { + cgraph::NodeValue::Value(DirValue::#key(NumValue { number: #number, refinement: #comp_type, })) @@ -539,7 +537,7 @@ impl GenContext { }; let compiled = quote! { - let #identifier = graph.make_value_node(#the_value, None, Vec::new(), None::<()>).expect("NodeId derivation failed"); + let #identifier = graph.make_value_node(#the_value, None, None::<()>); }; tokens.extend(compiled); @@ -581,7 +579,6 @@ impl GenContext { Vec::from_iter([#(#values_tokens),*]), None, None::<()>, - Vec::new(), ).expect("Failed to make In aggregator"); }; @@ -606,7 +603,7 @@ impl GenContext { for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); tokens.extend(quote! { - graph.make_edge(#from_node, #rhs_ident, Strength::#strength, Relation::#relation) + graph.make_edge(#from_node, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::#relation, None::<cgraph::DomainId>) .expect("Failed to make edge"); }); } @@ -614,16 +611,18 @@ impl GenContext { let mut all_agg_nodes: Vec<TokenStream> = Vec::with_capacity(node_details.len()); for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); - all_agg_nodes.push(quote! { (#from_node, Relation::#relation, Strength::Strong) }); + all_agg_nodes.push( + quote! { (#from_node, cgraph::Relation::#relation, cgraph::Strength::Strong) }, + ); } let strength = format_ident!("{}", rule.strength.to_string()); let (agg_node_ident, _) = self.next_node_ident(); tokens.extend(quote! { - let #agg_node_ident = graph.make_all_aggregator(&[#(#all_agg_nodes),*], None, None::<()>, Vec::new()) + let #agg_node_ident = graph.make_all_aggregator(&[#(#all_agg_nodes),*], None, None::<()>, None) .expect("Failed to make all aggregator node"); - graph.make_edge(#agg_node_ident, #rhs_ident, Strength::#strength, Relation::Positive) + graph.make_edge(#agg_node_ident, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::Positive, None::<cgraph::DomainId>) .expect("Failed to create all aggregator edge"); }); @@ -638,21 +637,10 @@ impl GenContext { self.compile_rule(rule, &mut tokens)?; } - let scope = match &program.scope { - Scope::Crate => quote! { crate }, - Scope::Extern => quote! { euclid }, - }; - let compiled = quote! {{ - use #scope::{ - dssa::graph::*, - types::*, - frontend::dir::{*, enums::*}, - }; - - use rustc_hash::{FxHashMap, FxHashSet}; + use euclid_graph_prelude::*; - let mut graph = KnowledgeGraphBuilder::new(); + let mut graph = cgraph::ConstraintGraphBuilder::new(); #tokens diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index 6f5d3ec9cc3..293940f27c4 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -23,6 +23,7 @@ payouts = ["api_models/payouts", "euclid/payouts"] [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } connector_configs = { version = "0.1.0", path = "../connector_configs" } euclid = { version = "0.1.0", path = "../euclid", features = [] } diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index 36af0dc2d23..4920243bcc0 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -20,11 +20,7 @@ use currency_conversion::{ }; use euclid::{ backend::{inputs, interpreter::InterpreterBackend, EuclidBackend}, - dssa::{ - self, analyzer, - graph::{self, Memoization}, - state_machine, truth, - }, + dssa::{self, analyzer, graph::CgraphExt, state_machine, truth}, frontend::{ ast, dir::{self, enums as dir_enums, EuclidDirFilter}, @@ -38,7 +34,7 @@ use crate::utils::JsResultExt; type JsResult = Result<JsValue, JsValue>; struct SeedData<'a> { - kgraph: graph::KnowledgeGraph<'a>, + cgraph: hyperswitch_constraint_graph::ConstraintGraph<'a, dir::DirValue>, connectors: Vec<ast::ConnectorChoice>, } @@ -98,11 +94,12 @@ pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult { let mca_graph = kgraph_utils::mca::make_mca_graph(mcas).err_to_js()?; let analysis_graph = - graph::KnowledgeGraph::combine(&mca_graph, &truth::ANALYSIS_GRAPH).err_to_js()?; + hyperswitch_constraint_graph::ConstraintGraph::combine(&mca_graph, &truth::ANALYSIS_GRAPH) + .err_to_js()?; SEED_DATA .set(SeedData { - kgraph: analysis_graph, + cgraph: analysis_graph, connectors, }) .map_err(|_| "Knowledge Graph has been already seeded".to_string()) @@ -138,8 +135,12 @@ pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult { // Standalone conjunctive context analysis to ensure the context itself is valid before // checking it against merchant's connectors seed_data - .kgraph - .perform_context_analysis(ctx, &mut Memoization::new()) + .cgraph + .perform_context_analysis( + ctx, + &mut hyperswitch_constraint_graph::Memoization::new(), + None, + ) .err_to_js()?; // Update conjunctive context and run analysis on all of merchant's connectors. @@ -150,9 +151,11 @@ pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult { let ctx_val = dssa::types::ContextValue::assertion(choice, &dummy_meta); ctx.push(ctx_val); - let analysis_result = seed_data - .kgraph - .perform_context_analysis(ctx, &mut Memoization::new()); + let analysis_result = seed_data.cgraph.perform_context_analysis( + ctx, + &mut hyperswitch_constraint_graph::Memoization::new(), + None, + ); if analysis_result.is_err() { invalid_connectors.insert(conn.clone()); } @@ -171,7 +174,7 @@ pub fn get_valid_connectors_for_rule(rule: JsValue) -> JsResult { #[wasm_bindgen(js_name = analyzeProgram)] pub fn analyze_program(js_program: JsValue) -> JsResult { let program: ast::Program<ConnectorSelection> = serde_wasm_bindgen::from_value(js_program)?; - analyzer::analyze(program, SEED_DATA.get().map(|sd| &sd.kgraph)).err_to_js()?; + analyzer::analyze(program, SEED_DATA.get().map(|sd| &sd.cgraph)).err_to_js()?; Ok(JsValue::NULL) } diff --git a/crates/hyperswitch_constraint_graph/Cargo.toml b/crates/hyperswitch_constraint_graph/Cargo.toml new file mode 100644 index 00000000000..425855a05b0 --- /dev/null +++ b/crates/hyperswitch_constraint_graph/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "hyperswitch_constraint_graph" +description = "Constraint Graph Framework for modeling Domain-Specific Constraints" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +erased-serde = "0.3.28" +rustc-hash = "1.1.0" +serde = { version = "1.0.163", features = ["derive", "rc"] } +serde_json = "1.0.96" +strum = { version = "0.25", features = ["derive"] } +thiserror = "1.0.43" diff --git a/crates/hyperswitch_constraint_graph/src/builder.rs b/crates/hyperswitch_constraint_graph/src/builder.rs new file mode 100644 index 00000000000..c1343eff885 --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/builder.rs @@ -0,0 +1,283 @@ +use std::sync::Arc; + +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::{ + dense_map::DenseMap, + error::GraphError, + graph::ConstraintGraph, + types::{ + DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId, Metadata, Node, NodeId, NodeType, + NodeValue, Relation, Strength, ValueNode, + }, +}; + +pub enum DomainIdOrIdentifier<'a> { + DomainId(DomainId), + DomainIdentifier(DomainIdentifier<'a>), +} + +impl<'a> From<&'a str> for DomainIdOrIdentifier<'a> { + fn from(value: &'a str) -> Self { + Self::DomainIdentifier(DomainIdentifier::new(value)) + } +} + +impl From<DomainId> for DomainIdOrIdentifier<'_> { + fn from(value: DomainId) -> Self { + Self::DomainId(value) + } +} + +pub struct ConstraintGraphBuilder<'a, V: ValueNode> { + domain: DenseMap<DomainId, DomainInfo<'a>>, + nodes: DenseMap<NodeId, Node<V>>, + edges: DenseMap<EdgeId, Edge>, + domain_identifier_map: FxHashMap<DomainIdentifier<'a>, DomainId>, + value_map: FxHashMap<NodeValue<V>, NodeId>, + edges_map: FxHashMap<(NodeId, NodeId, Option<DomainId>), EdgeId>, + node_info: DenseMap<NodeId, Option<&'static str>>, + node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>, +} + +#[allow(clippy::new_without_default)] +impl<'a, V> ConstraintGraphBuilder<'a, V> +where + V: ValueNode, +{ + pub fn new() -> Self { + Self { + domain: DenseMap::new(), + nodes: DenseMap::new(), + edges: DenseMap::new(), + domain_identifier_map: FxHashMap::default(), + value_map: FxHashMap::default(), + edges_map: FxHashMap::default(), + node_info: DenseMap::new(), + node_metadata: DenseMap::new(), + } + } + + pub fn build(self) -> ConstraintGraph<'a, V> { + ConstraintGraph { + domain: self.domain, + domain_identifier_map: self.domain_identifier_map, + nodes: self.nodes, + edges: self.edges, + value_map: self.value_map, + node_info: self.node_info, + node_metadata: self.node_metadata, + } + } + + fn retrieve_domain_from_identifier( + &self, + domain_ident: DomainIdentifier<'_>, + ) -> Result<DomainId, GraphError<V>> { + self.domain_identifier_map + .get(&domain_ident) + .copied() + .ok_or(GraphError::DomainNotFound) + } + + pub fn make_domain( + &mut self, + domain_identifier: &'a str, + domain_description: &str, + ) -> Result<DomainId, GraphError<V>> { + let domain_identifier = DomainIdentifier::new(domain_identifier); + Ok(self + .domain_identifier_map + .clone() + .get(&domain_identifier) + .map_or_else( + || { + let domain_id = self.domain.push(DomainInfo { + domain_identifier, + domain_description: domain_description.to_string(), + }); + self.domain_identifier_map + .insert(domain_identifier, domain_id); + domain_id + }, + |domain_id| *domain_id, + )) + } + + pub fn make_value_node<M: Metadata>( + &mut self, + value: NodeValue<V>, + info: Option<&'static str>, + metadata: Option<M>, + ) -> NodeId { + self.value_map.get(&value).copied().unwrap_or_else(|| { + let node_id = self.nodes.push(Node::new(NodeType::Value(value.clone()))); + let _node_info_id = self.node_info.push(info); + + let _node_metadata_id = self + .node_metadata + .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); + + self.value_map.insert(value, node_id); + node_id + }) + } + + pub fn make_edge<'short, T: Into<DomainIdOrIdentifier<'short>>>( + &mut self, + pred_id: NodeId, + succ_id: NodeId, + strength: Strength, + relation: Relation, + domain: Option<T>, + ) -> Result<EdgeId, GraphError<V>> { + self.ensure_node_exists(pred_id)?; + self.ensure_node_exists(succ_id)?; + let domain_id = domain + .map(|d| match d.into() { + DomainIdOrIdentifier::DomainIdentifier(ident) => { + self.retrieve_domain_from_identifier(ident) + } + DomainIdOrIdentifier::DomainId(domain_id) => { + self.ensure_domain_exists(domain_id).map(|_| domain_id) + } + }) + .transpose()?; + self.edges_map + .get(&(pred_id, succ_id, domain_id)) + .copied() + .and_then(|edge_id| self.edges.get(edge_id).cloned().map(|edge| (edge_id, edge))) + .map_or_else( + || { + let edge_id = self.edges.push(Edge { + strength, + relation, + pred: pred_id, + succ: succ_id, + domain: domain_id, + }); + self.edges_map + .insert((pred_id, succ_id, domain_id), edge_id); + + let pred = self + .nodes + .get_mut(pred_id) + .ok_or(GraphError::NodeNotFound)?; + pred.succs.push(edge_id); + + let succ = self + .nodes + .get_mut(succ_id) + .ok_or(GraphError::NodeNotFound)?; + succ.preds.push(edge_id); + + Ok(edge_id) + }, + |(edge_id, edge)| { + if edge.strength == strength && edge.relation == relation { + Ok(edge_id) + } else { + Err(GraphError::ConflictingEdgeCreated) + } + }, + ) + } + + pub fn make_all_aggregator<M: Metadata>( + &mut self, + nodes: &[(NodeId, Relation, Strength)], + info: Option<&'static str>, + metadata: Option<M>, + domain: Option<&str>, + ) -> Result<NodeId, GraphError<V>> { + nodes + .iter() + .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; + + let aggregator_id = self.nodes.push(Node::new(NodeType::AllAggregator)); + let _aggregator_info_id = self.node_info.push(info); + + let _node_metadata_id = self + .node_metadata + .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); + + for (node_id, relation, strength) in nodes { + self.make_edge(*node_id, aggregator_id, *strength, *relation, domain)?; + } + + Ok(aggregator_id) + } + + pub fn make_any_aggregator<M: Metadata>( + &mut self, + nodes: &[(NodeId, Relation, Strength)], + info: Option<&'static str>, + metadata: Option<M>, + domain: Option<&str>, + ) -> Result<NodeId, GraphError<V>> { + nodes + .iter() + .try_for_each(|(node_id, _, _)| self.ensure_node_exists(*node_id))?; + + let aggregator_id = self.nodes.push(Node::new(NodeType::AnyAggregator)); + let _aggregator_info_id = self.node_info.push(info); + + let _node_metadata_id = self + .node_metadata + .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); + + for (node_id, relation, strength) in nodes { + self.make_edge(*node_id, aggregator_id, *strength, *relation, domain)?; + } + + Ok(aggregator_id) + } + + pub fn make_in_aggregator<M: Metadata>( + &mut self, + values: Vec<V>, + info: Option<&'static str>, + metadata: Option<M>, + ) -> Result<NodeId, GraphError<V>> { + let key = values + .first() + .ok_or(GraphError::NoInAggregatorValues)? + .get_key(); + + for val in &values { + if val.get_key() != key { + Err(GraphError::MalformedGraph { + reason: "Values for 'In' aggregator not of same key".to_string(), + })?; + } + } + let node_id = self + .nodes + .push(Node::new(NodeType::InAggregator(FxHashSet::from_iter( + values, + )))); + let _aggregator_info_id = self.node_info.push(info); + + let _node_metadata_id = self + .node_metadata + .push(metadata.map(|meta| -> Arc<dyn Metadata> { Arc::new(meta) })); + + Ok(node_id) + } + + fn ensure_node_exists(&self, id: NodeId) -> Result<(), GraphError<V>> { + if self.nodes.contains_key(id) { + Ok(()) + } else { + Err(GraphError::NodeNotFound) + } + } + + fn ensure_domain_exists(&self, id: DomainId) -> Result<(), GraphError<V>> { + if self.domain.contains_key(id) { + Ok(()) + } else { + Err(GraphError::DomainNotFound) + } + } +} diff --git a/crates/euclid/src/utils/dense_map.rs b/crates/hyperswitch_constraint_graph/src/dense_map.rs similarity index 92% rename from crates/euclid/src/utils/dense_map.rs rename to crates/hyperswitch_constraint_graph/src/dense_map.rs index 8bd4487c77b..682833d65e6 100644 --- a/crates/euclid/src/utils/dense_map.rs +++ b/crates/hyperswitch_constraint_graph/src/dense_map.rs @@ -5,6 +5,24 @@ pub trait EntityId { fn with_id(id: usize) -> Self; } +macro_rules! impl_entity { + ($name:ident) => { + impl $crate::dense_map::EntityId for $name { + #[inline] + fn get_id(&self) -> usize { + self.0 + } + + #[inline] + fn with_id(id: usize) -> Self { + Self(id) + } + } + }; +} + +pub(crate) use impl_entity; + pub struct DenseMap<K, V> { data: Vec<V>, _marker: PhantomData<K>, diff --git a/crates/hyperswitch_constraint_graph/src/error.rs b/crates/hyperswitch_constraint_graph/src/error.rs new file mode 100644 index 00000000000..cd2269de264 --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/error.rs @@ -0,0 +1,77 @@ +use std::sync::{Arc, Weak}; + +use crate::types::{Metadata, NodeValue, Relation, RelationResolution, ValueNode}; + +#[derive(Debug, Clone, serde::Serialize)] +#[serde(tag = "type", content = "predecessor", rename_all = "snake_case")] +pub enum ValueTracePredecessor<V: ValueNode> { + Mandatory(Box<Weak<AnalysisTrace<V>>>), + OneOf(Vec<Weak<AnalysisTrace<V>>>), +} + +#[derive(Debug, Clone, serde::Serialize)] +#[serde(tag = "type", content = "trace", rename_all = "snake_case")] +pub enum AnalysisTrace<V: ValueNode> { + Value { + value: NodeValue<V>, + relation: Relation, + predecessors: Option<ValueTracePredecessor<V>>, + info: Option<&'static str>, + metadata: Option<Arc<dyn Metadata>>, + }, + + AllAggregation { + unsatisfied: Vec<Weak<AnalysisTrace<V>>>, + info: Option<&'static str>, + metadata: Option<Arc<dyn Metadata>>, + }, + + AnyAggregation { + unsatisfied: Vec<Weak<AnalysisTrace<V>>>, + info: Option<&'static str>, + metadata: Option<Arc<dyn Metadata>>, + }, + + InAggregation { + expected: Vec<V>, + found: Option<V>, + relation: Relation, + info: Option<&'static str>, + metadata: Option<Arc<dyn Metadata>>, + }, + Contradiction { + relation: RelationResolution, + }, +} + +#[derive(Debug, Clone, serde::Serialize, thiserror::Error)] +#[serde(tag = "type", content = "info", rename_all = "snake_case")] +pub enum GraphError<V: ValueNode> { + #[error("An edge was not found in the graph")] + EdgeNotFound, + #[error("Attempted to create a conflicting edge between two nodes")] + ConflictingEdgeCreated, + #[error("Cycle detected in graph")] + CycleDetected, + #[error("Domain wasn't found in the Graph")] + DomainNotFound, + #[error("Malformed Graph: {reason}")] + MalformedGraph { reason: String }, + #[error("A node was not found in the graph")] + NodeNotFound, + #[error("A value node was not found: {0:#?}")] + ValueNodeNotFound(V), + #[error("No values provided for an 'in' aggregator node")] + NoInAggregatorValues, + #[error("Error during analysis: {0:#?}")] + AnalysisError(Weak<AnalysisTrace<V>>), +} + +impl<V: ValueNode> GraphError<V> { + pub fn get_analysis_trace(self) -> Result<Weak<AnalysisTrace<V>>, Self> { + match self { + Self::AnalysisError(trace) => Ok(trace), + _ => Err(self), + } + } +} diff --git a/crates/hyperswitch_constraint_graph/src/graph.rs b/crates/hyperswitch_constraint_graph/src/graph.rs new file mode 100644 index 00000000000..d0a98e19520 --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/graph.rs @@ -0,0 +1,587 @@ +use std::sync::{Arc, Weak}; + +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::{ + builder, + dense_map::DenseMap, + error::{self, AnalysisTrace, GraphError}, + types::{ + CheckingContext, CycleCheck, DomainId, DomainIdentifier, DomainInfo, Edge, EdgeId, + Memoization, Metadata, Node, NodeId, NodeType, NodeValue, Relation, RelationResolution, + Strength, ValueNode, + }, +}; + +struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> { + ctx: &'a C, + node: &'a Node<V>, + node_id: NodeId, + relation: Relation, + strength: Strength, + memo: &'a mut Memoization<V>, + cycle_map: &'a mut CycleCheck, + domains: Option<&'a [DomainId]>, +} + +pub struct ConstraintGraph<'a, V: ValueNode> { + pub domain: DenseMap<DomainId, DomainInfo<'a>>, + pub domain_identifier_map: FxHashMap<DomainIdentifier<'a>, DomainId>, + pub nodes: DenseMap<NodeId, Node<V>>, + pub edges: DenseMap<EdgeId, Edge>, + pub value_map: FxHashMap<NodeValue<V>, NodeId>, + pub node_info: DenseMap<NodeId, Option<&'static str>>, + pub node_metadata: DenseMap<NodeId, Option<Arc<dyn Metadata>>>, +} + +impl<'a, V> ConstraintGraph<'a, V> +where + V: ValueNode, +{ + fn get_predecessor_edges_by_domain( + &self, + node_id: NodeId, + domains: Option<&[DomainId]>, + ) -> Result<Vec<&Edge>, GraphError<V>> { + let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; + let mut final_list = Vec::new(); + for &pred in &node.preds { + let edge = self.edges.get(pred).ok_or(GraphError::EdgeNotFound)?; + if let Some((domain_id, domains)) = edge.domain.zip(domains) { + if domains.contains(&domain_id) { + final_list.push(edge); + } + } else if edge.domain.is_none() { + final_list.push(edge); + } + } + + Ok(final_list) + } + + #[allow(clippy::too_many_arguments)] + pub fn check_node<C>( + &self, + ctx: &C, + node_id: NodeId, + relation: Relation, + strength: Strength, + memo: &mut Memoization<V>, + cycle_map: &mut CycleCheck, + domains: Option<&[&str]>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let domains = domains + .map(|domain_idents| { + domain_idents + .iter() + .map(|domain_ident| { + self.domain_identifier_map + .get(&DomainIdentifier::new(domain_ident)) + .copied() + .ok_or(GraphError::DomainNotFound) + }) + .collect::<Result<Vec<_>, _>>() + }) + .transpose()?; + + self.check_node_inner( + ctx, + node_id, + relation, + strength, + memo, + cycle_map, + domains.as_deref(), + ) + } + + #[allow(clippy::too_many_arguments)] + pub fn check_node_inner<C>( + &self, + ctx: &C, + node_id: NodeId, + relation: Relation, + strength: Strength, + memo: &mut Memoization<V>, + cycle_map: &mut CycleCheck, + domains: Option<&[DomainId]>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let node = self.nodes.get(node_id).ok_or(GraphError::NodeNotFound)?; + + if let Some(already_memo) = memo.get(&(node_id, relation, strength)) { + already_memo + .clone() + .map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err))) + } else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).cloned() + { + let strength_relation = Strength::get_resolved_strength(initial_strength, strength); + let relation_resolve = + RelationResolution::get_resolved_relation(initial_relation, relation.into()); + cycle_map.entry(node_id).and_modify(|value| { + value.0 = strength_relation; + value.1 = relation_resolve + }); + Ok(()) + } else { + let check_node_context = CheckNodeContext { + node, + node_id, + relation, + strength, + memo, + cycle_map, + ctx, + domains, + }; + match &node.node_type { + NodeType::AllAggregator => self.validate_all_aggregator(check_node_context), + + NodeType::AnyAggregator => self.validate_any_aggregator(check_node_context), + + NodeType::InAggregator(expected) => { + self.validate_in_aggregator(check_node_context, expected) + } + NodeType::Value(val) => self.validate_value_node(check_node_context, val), + } + } + } + + fn validate_all_aggregator<C>( + &self, + vald: CheckNodeContext<'_, V, C>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new(); + + for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { + vald.cycle_map + .insert(vald.node_id, (vald.strength, vald.relation.into())); + if let Err(e) = self.check_node_inner( + vald.ctx, + edge.pred, + edge.relation, + edge.strength, + vald.memo, + vald.cycle_map, + vald.domains, + ) { + unsatisfied.push(e.get_analysis_trace()?); + } + if let Some((_resolved_strength, resolved_relation)) = + vald.cycle_map.remove(&vald.node_id) + { + if resolved_relation == RelationResolution::Contradiction { + let err = Arc::new(AnalysisTrace::Contradiction { + relation: resolved_relation, + }); + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + return Err(GraphError::AnalysisError(Arc::downgrade(&err))); + } + } + } + + if !unsatisfied.is_empty() { + let err = Arc::new(AnalysisTrace::AllAggregation { + unsatisfied, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err))) + } else { + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } + } + + fn validate_any_aggregator<C>( + &self, + vald: CheckNodeContext<'_, V, C>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let mut unsatisfied = Vec::<Weak<AnalysisTrace<V>>>::new(); + let mut matched_one = false; + + for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { + vald.cycle_map + .insert(vald.node_id, (vald.strength, vald.relation.into())); + if let Err(e) = self.check_node_inner( + vald.ctx, + edge.pred, + edge.relation, + edge.strength, + vald.memo, + vald.cycle_map, + vald.domains, + ) { + unsatisfied.push(e.get_analysis_trace()?); + } else { + matched_one = true; + } + if let Some((_resolved_strength, resolved_relation)) = + vald.cycle_map.remove(&vald.node_id) + { + if resolved_relation == RelationResolution::Contradiction { + let err = Arc::new(AnalysisTrace::Contradiction { + relation: resolved_relation, + }); + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + + return Err(GraphError::AnalysisError(Arc::downgrade(&err))); + } + } + } + + if matched_one || vald.node.preds.is_empty() { + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } else { + let err = Arc::new(AnalysisTrace::AnyAggregation { + unsatisfied: unsatisfied.clone(), + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err))) + } + } + + fn validate_in_aggregator<C>( + &self, + vald: CheckNodeContext<'_, V, C>, + expected: &FxHashSet<V>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let the_key = expected + .iter() + .next() + .ok_or_else(|| GraphError::MalformedGraph { + reason: "An OnlyIn aggregator node must have at least one expected value" + .to_string(), + })? + .get_key(); + + let ctx_vals = if let Some(vals) = vald.ctx.get_values_by_key(&the_key) { + vals + } else { + return if let Strength::Weak = vald.strength { + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } else { + let err = Arc::new(AnalysisTrace::InAggregation { + expected: expected.iter().cloned().collect(), + found: None, + relation: vald.relation, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err))) + }; + }; + + let relation_bool: bool = vald.relation.into(); + for ctx_value in ctx_vals { + if expected.contains(&ctx_value) != relation_bool { + let err = Arc::new(AnalysisTrace::InAggregation { + expected: expected.iter().cloned().collect(), + found: Some(ctx_value.clone()), + relation: vald.relation, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; + } + } + + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } + + fn validate_value_node<C>( + &self, + vald: CheckNodeContext<'_, V, C>, + val: &NodeValue<V>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let mut errors = Vec::<Weak<AnalysisTrace<V>>>::new(); + let mut matched_one = false; + + self.context_analysis( + vald.node_id, + vald.relation, + vald.strength, + vald.ctx, + val, + vald.memo, + )?; + + for edge in self.get_predecessor_edges_by_domain(vald.node_id, vald.domains)? { + vald.cycle_map + .insert(vald.node_id, (vald.strength, vald.relation.into())); + let result = self.check_node_inner( + vald.ctx, + edge.pred, + edge.relation, + edge.strength, + vald.memo, + vald.cycle_map, + vald.domains, + ); + + if let Some((resolved_strength, resolved_relation)) = + vald.cycle_map.remove(&vald.node_id) + { + if resolved_relation == RelationResolution::Contradiction { + let err = Arc::new(AnalysisTrace::Contradiction { + relation: resolved_relation, + }); + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + return Err(GraphError::AnalysisError(Arc::downgrade(&err))); + } else if resolved_strength != vald.strength { + self.context_analysis( + vald.node_id, + vald.relation, + resolved_strength, + vald.ctx, + val, + vald.memo, + )? + } + } + match (edge.strength, result) { + (Strength::Strong, Err(trace)) => { + let err = Arc::new(AnalysisTrace::Value { + value: val.clone(), + relation: vald.relation, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + predecessors: Some(error::ValueTracePredecessor::Mandatory(Box::new( + trace.get_analysis_trace()?, + ))), + }); + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; + } + + (Strength::Strong, Ok(_)) => { + matched_one = true; + } + + (Strength::Normal | Strength::Weak, Err(trace)) => { + errors.push(trace.get_analysis_trace()?); + } + + (Strength::Normal | Strength::Weak, Ok(_)) => { + matched_one = true; + } + } + } + + if matched_one || vald.node.preds.is_empty() { + vald.memo + .insert((vald.node_id, vald.relation, vald.strength), Ok(())); + Ok(()) + } else { + let err = Arc::new(AnalysisTrace::Value { + value: val.clone(), + relation: vald.relation, + info: self.node_info.get(vald.node_id).cloned().flatten(), + metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), + predecessors: Some(error::ValueTracePredecessor::OneOf(errors.clone())), + }); + + vald.memo.insert( + (vald.node_id, vald.relation, vald.strength), + Err(Arc::clone(&err)), + ); + Err(GraphError::AnalysisError(Arc::downgrade(&err))) + } + } + + fn context_analysis<C>( + &self, + node_id: NodeId, + relation: Relation, + strength: Strength, + ctx: &C, + val: &NodeValue<V>, + memo: &mut Memoization<V>, + ) -> Result<(), GraphError<V>> + where + C: CheckingContext<Value = V>, + { + let in_context = ctx.check_presence(val, strength); + let relation_bool: bool = relation.into(); + if in_context != relation_bool { + let err = Arc::new(AnalysisTrace::Value { + value: val.clone(), + relation, + predecessors: None, + info: self.node_info.get(node_id).cloned().flatten(), + metadata: self.node_metadata.get(node_id).cloned().flatten(), + }); + memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); + Err(GraphError::AnalysisError(Arc::downgrade(&err)))?; + } + if !relation_bool { + memo.insert((node_id, relation, strength), Ok(())); + return Ok(()); + } + Ok(()) + } + + pub fn combine<'b>(g1: &'b Self, g2: &'b Self) -> Result<Self, GraphError<V>> { + let mut node_builder = builder::ConstraintGraphBuilder::new(); + let mut g1_old2new_id = DenseMap::<NodeId, NodeId>::new(); + let mut g2_old2new_id = DenseMap::<NodeId, NodeId>::new(); + let mut g1_old2new_domain_id = DenseMap::<DomainId, DomainId>::new(); + let mut g2_old2new_domain_id = DenseMap::<DomainId, DomainId>::new(); + + let add_domain = |node_builder: &mut builder::ConstraintGraphBuilder<'a, V>, + domain: DomainInfo<'a>| + -> Result<DomainId, GraphError<V>> { + node_builder.make_domain( + domain.domain_identifier.into_inner(), + &domain.domain_description, + ) + }; + + let add_node = |node_builder: &mut builder::ConstraintGraphBuilder<'a, V>, + node: &Node<V>| + -> Result<NodeId, GraphError<V>> { + match &node.node_type { + NodeType::Value(node_value) => { + Ok(node_builder.make_value_node(node_value.clone(), None, None::<()>)) + } + + NodeType::AllAggregator => { + Ok(node_builder.make_all_aggregator(&[], None, None::<()>, None)?) + } + + NodeType::AnyAggregator => { + Ok(node_builder.make_any_aggregator(&[], None, None::<()>, None)?) + } + + NodeType::InAggregator(expected) => Ok(node_builder.make_in_aggregator( + expected.iter().cloned().collect(), + None, + None::<()>, + )?), + } + }; + + for (_old_domain_id, domain) in g1.domain.iter() { + let new_domain_id = add_domain(&mut node_builder, domain.clone())?; + g1_old2new_domain_id.push(new_domain_id); + } + + for (_old_domain_id, domain) in g2.domain.iter() { + let new_domain_id = add_domain(&mut node_builder, domain.clone())?; + g2_old2new_domain_id.push(new_domain_id); + } + + for (_old_node_id, node) in g1.nodes.iter() { + let new_node_id = add_node(&mut node_builder, node)?; + g1_old2new_id.push(new_node_id); + } + + for (_old_node_id, node) in g2.nodes.iter() { + let new_node_id = add_node(&mut node_builder, node)?; + g2_old2new_id.push(new_node_id); + } + + for edge in g1.edges.values() { + let new_pred_id = g1_old2new_id + .get(edge.pred) + .ok_or(GraphError::NodeNotFound)?; + let new_succ_id = g1_old2new_id + .get(edge.succ) + .ok_or(GraphError::NodeNotFound)?; + let domain_ident = edge + .domain + .map(|domain_id| g1.domain.get(domain_id).ok_or(GraphError::DomainNotFound)) + .transpose()? + .map(|domain| domain.domain_identifier); + + node_builder.make_edge( + *new_pred_id, + *new_succ_id, + edge.strength, + edge.relation, + domain_ident.as_deref(), + )?; + } + + for edge in g2.edges.values() { + let new_pred_id = g2_old2new_id + .get(edge.pred) + .ok_or(GraphError::NodeNotFound)?; + let new_succ_id = g2_old2new_id + .get(edge.succ) + .ok_or(GraphError::NodeNotFound)?; + let domain_ident = edge + .domain + .map(|domain_id| g2.domain.get(domain_id).ok_or(GraphError::DomainNotFound)) + .transpose()? + .map(|domain| domain.domain_identifier); + + node_builder.make_edge( + *new_pred_id, + *new_succ_id, + edge.strength, + edge.relation, + domain_ident.as_deref(), + )?; + } + + Ok(node_builder.build()) + } +} diff --git a/crates/hyperswitch_constraint_graph/src/lib.rs b/crates/hyperswitch_constraint_graph/src/lib.rs new file mode 100644 index 00000000000..ade9a64272f --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/lib.rs @@ -0,0 +1,13 @@ +pub mod builder; +mod dense_map; +pub mod error; +pub mod graph; +pub mod types; + +pub use builder::ConstraintGraphBuilder; +pub use error::{AnalysisTrace, GraphError}; +pub use graph::ConstraintGraph; +pub use types::{ + CheckingContext, CycleCheck, DomainId, DomainIdentifier, Edge, EdgeId, KeyNode, Memoization, + Node, NodeId, NodeValue, Relation, Strength, ValueNode, +}; diff --git a/crates/hyperswitch_constraint_graph/src/types.rs b/crates/hyperswitch_constraint_graph/src/types.rs new file mode 100644 index 00000000000..d1d14bd7e5c --- /dev/null +++ b/crates/hyperswitch_constraint_graph/src/types.rs @@ -0,0 +1,249 @@ +use std::{ + any::Any, + fmt, hash, + ops::{Deref, DerefMut}, + sync::Arc, +}; + +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::{dense_map::impl_entity, error::AnalysisTrace}; + +pub trait KeyNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq {} + +pub trait ValueNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + PartialEq + Eq { + type Key: KeyNode; + + fn get_key(&self) -> Self::Key; +} + +#[derive(Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash)] +#[serde(transparent)] +pub struct NodeId(usize); + +impl_entity!(NodeId); + +#[derive(Debug)] +pub struct Node<V: ValueNode> { + pub node_type: NodeType<V>, + pub preds: Vec<EdgeId>, + pub succs: Vec<EdgeId>, +} + +impl<V: ValueNode> Node<V> { + pub(crate) fn new(node_type: NodeType<V>) -> Self { + Self { + node_type, + preds: Vec::new(), + succs: Vec::new(), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum NodeType<V: ValueNode> { + AllAggregator, + AnyAggregator, + InAggregator(FxHashSet<V>), + Value(NodeValue<V>), +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)] +#[serde(tag = "type", content = "value", rename_all = "snake_case")] +pub enum NodeValue<V: ValueNode> { + Key(<V as ValueNode>::Key), + Value(V), +} + +impl<V: ValueNode> From<V> for NodeValue<V> { + fn from(value: V) -> Self { + Self::Value(value) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct EdgeId(usize); + +impl_entity!(EdgeId); + +#[derive( + Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash, strum::Display, PartialOrd, Ord, +)] +pub enum Strength { + Weak, + Normal, + Strong, +} + +impl Strength { + pub fn get_resolved_strength(prev_strength: Self, curr_strength: Self) -> Self { + std::cmp::max(prev_strength, curr_strength) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Relation { + Positive, + Negative, +} + +impl From<Relation> for bool { + fn from(value: Relation) -> Self { + matches!(value, Relation::Positive) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, serde::Serialize)] +pub enum RelationResolution { + Positive, + Negative, + Contradiction, +} + +impl From<Relation> for RelationResolution { + fn from(value: Relation) -> Self { + match value { + Relation::Positive => Self::Positive, + Relation::Negative => Self::Negative, + } + } +} + +impl RelationResolution { + pub fn get_resolved_relation(prev_relation: Self, curr_relation: Self) -> Self { + if prev_relation != curr_relation { + Self::Contradiction + } else { + curr_relation + } + } +} + +#[derive(Debug, Clone)] +pub struct Edge { + pub strength: Strength, + pub relation: Relation, + pub pred: NodeId, + pub succ: NodeId, + pub domain: Option<DomainId>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct DomainId(usize); + +impl_entity!(DomainId); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct DomainIdentifier<'a>(&'a str); + +impl<'a> DomainIdentifier<'a> { + pub fn new(identifier: &'a str) -> Self { + Self(identifier) + } + + pub fn into_inner(&self) -> &'a str { + self.0 + } +} + +impl<'a> From<&'a str> for DomainIdentifier<'a> { + fn from(value: &'a str) -> Self { + Self(value) + } +} + +impl<'a> Deref for DomainIdentifier<'a> { + type Target = str; + + fn deref(&self) -> &'a Self::Target { + self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct DomainInfo<'a> { + pub domain_identifier: DomainIdentifier<'a>, + pub domain_description: String, +} + +pub trait CheckingContext { + type Value: ValueNode; + + fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self + where + L: Into<Self::Value>; + + fn check_presence(&self, value: &NodeValue<Self::Value>, strength: Strength) -> bool; + + fn get_values_by_key( + &self, + expected: &<Self::Value as ValueNode>::Key, + ) -> Option<Vec<Self::Value>>; +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct Memoization<V: ValueNode>( + #[allow(clippy::type_complexity)] + FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>, +); + +impl<V: ValueNode> Memoization<V> { + pub fn new() -> Self { + Self(FxHashMap::default()) + } +} + +impl<V: ValueNode> Default for Memoization<V> { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl<V: ValueNode> Deref for Memoization<V> { + type Target = FxHashMap<(NodeId, Relation, Strength), Result<(), Arc<AnalysisTrace<V>>>>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<V: ValueNode> DerefMut for Memoization<V> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +#[derive(Debug, Clone)] +pub struct CycleCheck(FxHashMap<NodeId, (Strength, RelationResolution)>); +impl CycleCheck { + pub fn new() -> Self { + Self(FxHashMap::default()) + } +} + +impl Default for CycleCheck { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl Deref for CycleCheck { + type Target = FxHashMap<NodeId, (Strength, RelationResolution)>; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for CycleCheck { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +pub trait Metadata: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {} +erased_serde::serialize_trait_object!(Metadata); + +impl<M> Metadata for M where M: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {} diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml index 4ad5ef04f42..86de6002c32 100644 --- a/crates/kgraph_utils/Cargo.toml +++ b/crates/kgraph_utils/Cargo.toml @@ -13,6 +13,7 @@ connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connect [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } common_enums = { version = "0.1.0", path = "../common_enums" } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } euclid = { version = "0.1.0", path = "../euclid" } masking = { version = "0.1.0", path = "../masking/" } diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs index 6105dc85d7e..9921ee7af35 100644 --- a/crates/kgraph_utils/benches/evaluation.rs +++ b/crates/kgraph_utils/benches/evaluation.rs @@ -8,13 +8,17 @@ use api_models::{ use criterion::{black_box, criterion_group, criterion_main, Criterion}; use euclid::{ dirval, - dssa::graph::{self, Memoization}, + dssa::graph::{self, CgraphExt}, frontend::dir, types::{NumValue, NumValueRefinement}, }; +use hyperswitch_constraint_graph::{CycleCheck, Memoization}; use kgraph_utils::{error::KgraphError, transformers::IntoDirValue}; -fn build_test_data<'a>(total_enabled: usize, total_pm_types: usize) -> graph::KnowledgeGraph<'a> { +fn build_test_data<'a>( + total_enabled: usize, + total_pm_types: usize, +) -> hyperswitch_constraint_graph::ConstraintGraph<'a, dir::DirValue> { use api_models::{admin::*, payment_methods::*}; let mut pms_enabled: Vec<PaymentMethodsEnabled> = Vec::new(); @@ -88,6 +92,8 @@ fn evaluation(c: &mut Criterion) { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); }); }); @@ -105,6 +111,8 @@ fn evaluation(c: &mut Criterion) { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); }); }); diff --git a/crates/kgraph_utils/src/error.rs b/crates/kgraph_utils/src/error.rs index 5a16c6375b0..95450fbe350 100644 --- a/crates/kgraph_utils/src/error.rs +++ b/crates/kgraph_utils/src/error.rs @@ -1,4 +1,4 @@ -use euclid::dssa::{graph::GraphError, types::AnalysisErrorType}; +use euclid::{dssa::types::AnalysisErrorType, frontend::dir}; #[derive(Debug, thiserror::Error, serde::Serialize)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] @@ -6,7 +6,7 @@ pub enum KgraphError { #[error("Invalid connector name encountered: '{0}'")] InvalidConnectorName(String), #[error("There was an error constructing the graph: {0}")] - GraphConstructionError(GraphError), + GraphConstructionError(hyperswitch_constraint_graph::GraphError<dir::DirValue>), #[error("There was an error constructing the context")] ContextConstructionError(AnalysisErrorType), #[error("there was an unprecedented indexing error")] diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 8542437a5a6..14a88dd1c6e 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -4,42 +4,39 @@ use api_models::{ admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes, }; use euclid::{ - dssa::graph::{self, DomainIdentifier}, frontend::{ast, dir}, types::{NumValue, NumValueRefinement}, }; +use hyperswitch_constraint_graph as cgraph; use crate::{error::KgraphError, transformers::IntoDirValue}; pub const DOMAIN_IDENTIFIER: &str = "payment_methods_enabled_for_merchantconnectoraccount"; fn compile_request_pm_types( - builder: &mut graph::KnowledgeGraphBuilder<'_>, + builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, pm_types: RequestPaymentMethodTypes, pm: api_enums::PaymentMethod, -) -> Result<graph::NodeId, KgraphError> { - let mut agg_nodes: Vec<(graph::NodeId, graph::Relation, graph::Strength)> = Vec::new(); +) -> Result<cgraph::NodeId, KgraphError> { + let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let pmt_info = "PaymentMethodType"; - let pmt_id = builder - .make_value_node( - (pm_types.payment_method_type, pm) - .into_dir_value() - .map(Into::into)?, - Some(pmt_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let pmt_id = builder.make_value_node( + (pm_types.payment_method_type, pm) + .into_dir_value() + .map(Into::into)?, + Some(pmt_info), + None::<()>, + ); agg_nodes.push(( pmt_id, - graph::Relation::Positive, + cgraph::Relation::Positive, match pm_types.payment_method_type { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { - graph::Strength::Weak + cgraph::Strength::Weak } - _ => graph::Strength::Strong, + _ => cgraph::Strength::Strong, }, )); @@ -52,13 +49,13 @@ fn compile_request_pm_types( let card_network_info = "Card Networks"; let card_network_id = builder - .make_in_aggregator(dir_vals, Some(card_network_info), None::<()>, Vec::new()) + .make_in_aggregator(dir_vals, Some(card_network_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( card_network_id, - graph::Relation::Positive, - graph::Strength::Weak, + cgraph::Relation::Positive, + cgraph::Strength::Weak, )); } } @@ -71,7 +68,7 @@ fn compile_request_pm_types( .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, - graph::Relation::Positive, + cgraph::Relation::Positive, )), admin_api::AcceptedCurrencies::DisableOnly(curr) if !curr.is_empty() => Some(( @@ -79,7 +76,7 @@ fn compile_request_pm_types( .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, - graph::Relation::Negative, + cgraph::Relation::Negative, )), _ => None, @@ -88,15 +85,10 @@ fn compile_request_pm_types( if let Some((currencies, relation)) = currencies_data { let accepted_currencies_info = "Accepted Currencies"; let accepted_currencies_id = builder - .make_in_aggregator( - currencies, - Some(accepted_currencies_info), - None::<()>, - Vec::new(), - ) + .make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; - agg_nodes.push((accepted_currencies_id, relation, graph::Strength::Strong)); + agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong)); } let mut amount_nodes = Vec::with_capacity(2); @@ -108,14 +100,11 @@ fn compile_request_pm_types( }; let min_amt_info = "Minimum Amount"; - let min_amt_id = builder - .make_value_node( - dir::DirValue::PaymentAmount(num_val).into(), - Some(min_amt_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let min_amt_id = builder.make_value_node( + dir::DirValue::PaymentAmount(num_val).into(), + Some(min_amt_info), + None::<()>, + ); amount_nodes.push(min_amt_id); } @@ -127,14 +116,11 @@ fn compile_request_pm_types( }; let max_amt_info = "Maximum Amount"; - let max_amt_id = builder - .make_value_node( - dir::DirValue::PaymentAmount(num_val).into(), - Some(max_amt_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let max_amt_id = builder.make_value_node( + dir::DirValue::PaymentAmount(num_val).into(), + Some(max_amt_info), + None::<()>, + ); amount_nodes.push(max_amt_id); } @@ -145,14 +131,11 @@ fn compile_request_pm_types( refinement: None, }; - let zero_amt_id = builder - .make_value_node( - dir::DirValue::PaymentAmount(zero_num_val).into(), - Some("zero_amount"), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let zero_amt_id = builder.make_value_node( + dir::DirValue::PaymentAmount(zero_num_val).into(), + Some("zero_amount"), + None::<()>, + ); let or_node_neighbor_id = if amount_nodes.len() == 1 { amount_nodes @@ -163,7 +146,13 @@ fn compile_request_pm_types( let nodes = amount_nodes .iter() .copied() - .map(|node_id| (node_id, graph::Relation::Positive, graph::Strength::Strong)) + .map(|node_id| { + ( + node_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + ) + }) .collect::<Vec<_>>(); builder @@ -171,7 +160,7 @@ fn compile_request_pm_types( &nodes, Some("amount_constraint_aggregator"), None::<()>, - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], + None, ) .map_err(KgraphError::GraphConstructionError)? }; @@ -179,37 +168,40 @@ fn compile_request_pm_types( let any_aggregator = builder .make_any_aggregator( &[ - (zero_amt_id, graph::Relation::Positive), - (or_node_neighbor_id, graph::Relation::Positive), + ( + zero_amt_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + ), + ( + or_node_neighbor_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + ), ], Some("zero_plus_limits_amount_aggregator"), None::<()>, - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], + None, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( any_aggregator, - graph::Relation::Positive, - graph::Strength::Strong, + cgraph::Relation::Positive, + cgraph::Strength::Strong, )); } let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType"; builder - .make_all_aggregator( - &agg_nodes, - Some(pmt_all_aggregator_info), - None::<()>, - Vec::new(), - ) + .make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError) } fn compile_payment_method_enabled( - builder: &mut graph::KnowledgeGraphBuilder<'_>, + builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, enabled: admin_api::PaymentMethodsEnabled, -) -> Result<Option<graph::NodeId>, KgraphError> { +) -> Result<Option<cgraph::NodeId>, KgraphError> { let agg_id = if !enabled .payment_method_types .as_ref() @@ -217,48 +209,44 @@ fn compile_payment_method_enabled( .unwrap_or(true) { let pm_info = "PaymentMethod"; - let pm_id = builder - .make_value_node( - enabled.payment_method.into_dir_value().map(Into::into)?, - Some(pm_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let pm_id = builder.make_value_node( + enabled.payment_method.into_dir_value().map(Into::into)?, + Some(pm_info), + None::<()>, + ); - let mut agg_nodes: Vec<(graph::NodeId, graph::Relation)> = Vec::new(); + let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pm_types) = enabled.payment_method_types { for pm_type in pm_types { let node_id = compile_request_pm_types(builder, pm_type, enabled.payment_method)?; - agg_nodes.push((node_id, graph::Relation::Positive)); + agg_nodes.push(( + node_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + )); } } let any_aggregator_info = "Any aggregation for PaymentMethodsType"; let pm_type_agg_id = builder - .make_any_aggregator( - &agg_nodes, - Some(any_aggregator_info), - None::<()>, - Vec::new(), - ) + .make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let all_aggregator_info = "All aggregation for PaymentMethod"; let enabled_pm_agg_id = builder .make_all_aggregator( &[ - (pm_id, graph::Relation::Positive, graph::Strength::Strong), + (pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong), ( pm_type_agg_id, - graph::Relation::Positive, - graph::Strength::Strong, + cgraph::Relation::Positive, + cgraph::Strength::Strong, ), ], Some(all_aggregator_info), None::<()>, - Vec::new(), + None, ) .map_err(KgraphError::GraphConstructionError)?; @@ -271,26 +259,30 @@ fn compile_payment_method_enabled( } fn compile_merchant_connector_graph( - builder: &mut graph::KnowledgeGraphBuilder<'_>, + builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>, mca: admin_api::MerchantConnectorResponse, ) -> Result<(), KgraphError> { let connector = common_enums::RoutableConnectors::from_str(&mca.connector_name) .map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name.clone()))?; - let mut agg_nodes: Vec<(graph::NodeId, graph::Relation)> = Vec::new(); + let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pms_enabled) = mca.payment_methods_enabled { for pm_enabled in pms_enabled { let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?; if let Some(pm_enabled_id) = maybe_pm_enabled_id { - agg_nodes.push((pm_enabled_id, graph::Relation::Positive)); + agg_nodes.push(( + pm_enabled_id, + cgraph::Relation::Positive, + cgraph::Strength::Strong, + )); } } } let aggregator_info = "Available Payment methods for connector"; let pms_enabled_agg_id = builder - .make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, Vec::new()) + .make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice { @@ -300,21 +292,16 @@ fn compile_merchant_connector_graph( })); let connector_info = "Connector"; - let connector_node_id = builder - .make_value_node( - connector_dir_val.into(), - Some(connector_info), - vec![DomainIdentifier::new(DOMAIN_IDENTIFIER)], - None::<()>, - ) - .map_err(KgraphError::GraphConstructionError)?; + let connector_node_id = + builder.make_value_node(connector_dir_val.into(), Some(connector_info), None::<()>); builder .make_edge( pms_enabled_agg_id, connector_node_id, - graph::Strength::Normal, - graph::Relation::Positive, + cgraph::Strength::Normal, + cgraph::Relation::Positive, + None::<cgraph::DomainId>, ) .map_err(KgraphError::GraphConstructionError)?; @@ -323,11 +310,11 @@ fn compile_merchant_connector_graph( pub fn make_mca_graph<'a>( accts: Vec<admin_api::MerchantConnectorResponse>, -) -> Result<graph::KnowledgeGraph<'a>, KgraphError> { - let mut builder = graph::KnowledgeGraphBuilder::new(); +) -> Result<cgraph::ConstraintGraph<'a, dir::DirValue>, KgraphError> { + let mut builder = cgraph::ConstraintGraphBuilder::new(); let _domain = builder.make_domain( - DomainIdentifier::new(DOMAIN_IDENTIFIER), - "Payment methods enabled for MerchantConnectorAccount".to_string(), + DOMAIN_IDENTIFIER, + "Payment methods enabled for MerchantConnectorAccount", ); for acct in accts { compile_merchant_connector_graph(&mut builder, acct)?; @@ -343,12 +330,13 @@ mod tests { use api_models::enums as api_enums; use euclid::{ dirval, - dssa::graph::{AnalysisContext, Memoization}, + dssa::graph::{AnalysisContext, CgraphExt}, }; + use hyperswitch_constraint_graph::{ConstraintGraph, CycleCheck, Memoization}; use super::*; - fn build_test_data<'a>() -> graph::KnowledgeGraph<'a> { + fn build_test_data<'a>() -> ConstraintGraph<'a, dir::DirValue> { use api_models::{admin::*, payment_methods::*}; let stripe_account = MerchantConnectorResponse { @@ -428,6 +416,8 @@ mod tests { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -448,6 +438,8 @@ mod tests { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_ok()); @@ -468,6 +460,8 @@ mod tests { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -488,6 +482,8 @@ mod tests { dirval!(PaymentAmount = 7), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_err()); @@ -507,6 +503,8 @@ mod tests { dirval!(PaymentAmount = 7), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); //println!("{:#?}", result); @@ -529,6 +527,8 @@ mod tests { dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); //println!("{:#?}", result); @@ -725,6 +725,8 @@ mod tests { dirval!(Connector = Stripe), &context, &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_ok(), "stripe validation failed"); @@ -733,6 +735,8 @@ mod tests { dirval!(Connector = Bluesnap), &context, &mut Memoization::new(), + &mut CycleCheck::new(), + None, ); assert!(result.is_err(), "bluesnap validation failed"); } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index f8e2cfad126..7ff47b927d8 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -103,6 +103,7 @@ analytics = { version = "0.1.0", path = "../analytics", optional = true } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs"] } +hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index ff7303c900d..6967c977753 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -17,9 +17,9 @@ use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ backend::{self, inputs as dsl_inputs, EuclidBackend}, - dssa::graph::{self as euclid_graph, Memoization}, + dssa::graph::{self as euclid_graph, CgraphExt}, enums as euclid_enums, - frontend::ast, + frontend::{ast, dir as euclid_dir}, }; use kgraph_utils::{ mca as mca_graph, @@ -82,7 +82,9 @@ pub struct SessionRoutingPmTypeInput<'a> { profile_id: Option<String>, } static ROUTING_CACHE: StaticCache<CachedAlgorithm> = StaticCache::new(); -static KGRAPH_CACHE: StaticCache<euclid_graph::KnowledgeGraph<'_>> = StaticCache::new(); +static KGRAPH_CACHE: StaticCache< + hyperswitch_constraint_graph::ConstraintGraph<'_, euclid_dir::DirValue>, +> = StaticCache::new(); type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>; @@ -542,7 +544,7 @@ pub async fn get_merchant_kgraph<'a>( merchant_last_modified: i64, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, transaction_type: &api_enums::TransactionType, -) -> RoutingResult<Arc<euclid_graph::KnowledgeGraph<'a>>> { +) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<'a, euclid_dir::DirValue>>> { let merchant_id = &key_store.merchant_id; #[cfg(feature = "business_profile_routing")] @@ -690,7 +692,13 @@ async fn perform_kgraph_filtering( .into_dir_value() .change_context(errors::RoutingError::KgraphAnalysisError)?; let kgraph_eligible = cached_kgraph - .check_value_validity(dir_val, &context, &mut Memoization::new()) + .check_value_validity( + dir_val, + &context, + &mut hyperswitch_constraint_graph::Memoization::new(), + &mut hyperswitch_constraint_graph::CycleCheck::new(), + None, + ) .change_context(errors::RoutingError::KgraphAnalysisError)?; let filter_eligible =
2023-12-06T13:01:25Z
## Description <!-- Describe your changes in detail --> This PR separates out and refactors the Euclid Knowledge Graph into the Constraint Graph in its own crate, and makes the Constraint Graph generic so it can work on custom key and value types as opposed to just the Euclid Key and Value types. This will remove the dependency on Euclid when one needs to only use the Constraint Graph, plus the now generic nature of Constraint Graphs will allow them to be utilized for varied use cases other than routing. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Making the constraint graph generic opens up the opportunity for other developers to adapt and use the constraint graph for their own usecases. There are many validation use cases currently in Hyperswitch that can be fulfilled by using Constraint Graphs, including but not limited to Connector domain validations, required field selection, etc. #
ecc97bc8684d57834f62652265316df29cf2cf5d
Unit tests for the `euclid` and `kgraph_utils` crates. No specific API tests required. Euclid: <img width="586" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/86ce0f9b-200b-4da7-903e-bf1c49d22c63"> Kgraph_utils: <img width="586" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/7fbb186d-8545-4da8-81b1-7d1f4f612d4c">
[ "Cargo.lock", "crates/euclid/Cargo.toml", "crates/euclid/src/dssa/analyzer.rs", "crates/euclid/src/dssa/graph.rs", "crates/euclid/src/dssa/truth.rs", "crates/euclid/src/dssa/types.rs", "crates/euclid/src/lib.rs", "crates/euclid/src/utils.rs", "crates/euclid_macros/src/inner/knowledge.rs", "crates/...
juspay/hyperswitch
juspay__hyperswitch-3439
Bug: [FEATURE] `Blocklist` initial implementation ### Feature Description: This feature provides merchants with the ability to customize their transaction controls based on specific criteria. Merchants can tailor the blocklist according to their preferences, blocking the following elements as needed: Card Numbers Card ISINs Extended BINs Understanding Blocklist: In the realm of payment processing, a blocklist serves as a security feature empowering merchants to restrict specific identifiers associated with payment methods or block certain card BINs. A fingerprint, a unique identifier linked to a payment method, and a card BIN, encompassing the first six digits of a credit card number, are key components. An extended card BIN covers the first eight digits. ### Testing Refer to the attached postman collection for the API contracts for the blocklist APIs. Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin. [blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip) ``` For Card Bin and Extended Card Bin :- 1. Setup a Merchant Account and any Connector account 2. Make a payment with a certain card (ensure it succeeds) 3. Block the card's card bin or extended card bin 4. Try the payment again (should fail this time with an API response saying that the payment was blocked) For Payment Instrument :- 1. Repeat steps 1 and 2 of previous section 2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card. 3. Try the payment again (should fail) ```
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs new file mode 100644 index 00000000000..fc838eed5ce --- /dev/null +++ b/crates/api_models/src/blocklist.rs @@ -0,0 +1,41 @@ +use common_enums::enums; +use common_utils::events::ApiEventMetric; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case", tag = "type", content = "data")] +pub enum BlocklistRequest { + CardBin(String), + Fingerprint(String), + ExtendedCardBin(String), +} + +pub type AddToBlocklistRequest = BlocklistRequest; +pub type DeleteFromBlocklistRequest = BlocklistRequest; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct BlocklistResponse { + pub fingerprint_id: String, + pub data_kind: enums::BlocklistDataKind, + #[serde(with = "common_utils::custom_serde::iso8601")] + pub created_at: time::PrimitiveDateTime, +} + +pub type AddToBlocklistResponse = BlocklistResponse; +pub type DeleteFromBlocklistResponse = BlocklistResponse; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ListBlocklistQuery { + pub data_kind: enums::BlocklistDataKind, + #[serde(default = "default_list_limit")] + pub limit: u16, + #[serde(default)] + pub offset: u16, +} + +fn default_list_limit() -> u16 { + 10 +} + +impl ApiEventMetric for BlocklistRequest {} +impl ApiEventMetric for BlocklistResponse {} +impl ApiEventMetric for ListBlocklistQuery {} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index 459443747e3..dc1f6eb6537 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -3,6 +3,7 @@ pub mod admin; pub mod analytics; pub mod api_keys; pub mod bank_accounts; +pub mod blocklist; pub mod cards_info; pub mod conditional_configs; pub mod connector_onboarding; diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 45611a91458..f9077500dd4 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2274,6 +2274,9 @@ pub struct PaymentsResponse { /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, + + /// Payment Fingerprint + pub fingerprint: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index ca47c73c7c2..87b04baa1a2 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -24,6 +24,13 @@ impl CardNumber { pub fn get_card_isin(self) -> String { self.0.peek().chars().take(6).collect::<String>() } + + pub fn get_extended_card_bin(self) -> String { + self.0.peek().chars().take(8).collect::<String>() + } + pub fn get_card_no(self) -> String { + self.0.peek().chars().collect::<String>() + } pub fn get_last4(self) -> String { self.0 .peek() diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 3af1c0e826b..949cc2e0034 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -6,12 +6,13 @@ use utoipa::ToSchema; pub mod diesel_exports { pub use super::{ DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, - DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, - DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, - DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbEventType as EventType, - DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, - DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, - DbPaymentType as PaymentType, DbRefundStatus as RefundStatus, + DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, + DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType, + DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDisputeStage as DisputeStage, + DbDisputeStatus as DisputeStatus, DbEventType as EventType, DbFutureUsage as FutureUsage, + DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, + DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, + DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, }; } @@ -275,6 +276,27 @@ pub enum AuthorizationStatus { Unresolved, } +#[derive( + Clone, + Debug, + PartialEq, + Eq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, + Hash, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum BlocklistDataKind { + PaymentMethod, + CardBin, + ExtendedCardBin, +} + #[derive( Clone, Copy, diff --git a/crates/data_models/src/errors.rs b/crates/data_models/src/errors.rs index 9616a3a944c..bed1ab9ccbf 100644 --- a/crates/data_models/src/errors.rs +++ b/crates/data_models/src/errors.rs @@ -24,6 +24,8 @@ pub enum StorageError { SerializationFailed, #[error("MockDb error")] MockDbError, + #[error("Kafka error")] + KafkaError, #[error("Customer with this id is Redacted")] CustomerRedacted, #[error("Deserialization failure")] diff --git a/crates/data_models/src/payments.rs b/crates/data_models/src/payments.rs index cc6b03f89a5..713003d666b 100644 --- a/crates/data_models/src/payments.rs +++ b/crates/data_models/src/payments.rs @@ -53,5 +53,6 @@ pub struct PaymentIntent { pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, + pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, } diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs index 80671ec7f61..7470b5f8502 100644 --- a/crates/data_models/src/payments/payment_intent.rs +++ b/crates/data_models/src/payments/payment_intent.rs @@ -110,6 +110,7 @@ pub struct PaymentIntentNew { pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, + pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, } @@ -163,6 +164,7 @@ pub enum PaymentIntentUpdate { metadata: Option<pii::SecretSerdeValue>, payment_confirm_source: Option<storage_enums::PaymentSource>, updated_by: String, + fingerprint_id: Option<String>, session_expiry: Option<PrimitiveDateTime>, }, PaymentAttemptAndAttemptCountUpdate { @@ -228,6 +230,7 @@ pub struct PaymentIntentUpdateInternal { pub surcharge_applicable: Option<bool>, pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, + pub fingerprint_id: Option<String>, pub session_expiry: Option<PrimitiveDateTime>, } @@ -252,6 +255,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { metadata, payment_confirm_source, updated_by, + fingerprint_id, session_expiry, } => Self { amount: Some(amount), @@ -272,6 +276,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { metadata, payment_confirm_source, updated_by, + fingerprint_id, session_expiry, ..Default::default() }, diff --git a/crates/diesel_models/src/blocklist.rs b/crates/diesel_models/src/blocklist.rs new file mode 100644 index 00000000000..9e88802aa3b --- /dev/null +++ b/crates/diesel_models/src/blocklist.rs @@ -0,0 +1,26 @@ +use diesel::{Identifiable, Insertable, Queryable}; +use serde::{Deserialize, Serialize}; + +use crate::schema::blocklist; + +#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] +#[diesel(table_name = blocklist)] +pub struct BlocklistNew { + pub merchant_id: String, + pub fingerprint_id: String, + pub data_kind: common_enums::BlocklistDataKind, + pub metadata: Option<serde_json::Value>, + pub created_at: time::PrimitiveDateTime, +} + +#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Deserialize, Serialize)] +#[diesel(table_name = blocklist)] +pub struct Blocklist { + #[serde(skip)] + pub id: i32, + pub merchant_id: String, + pub fingerprint_id: String, + pub data_kind: common_enums::BlocklistDataKind, + pub metadata: Option<serde_json::Value>, + pub created_at: time::PrimitiveDateTime, +} diff --git a/crates/diesel_models/src/blocklist_fingerprint.rs b/crates/diesel_models/src/blocklist_fingerprint.rs new file mode 100644 index 00000000000..e75856622e2 --- /dev/null +++ b/crates/diesel_models/src/blocklist_fingerprint.rs @@ -0,0 +1,26 @@ +use diesel::{Identifiable, Insertable, Queryable}; +use serde::{Deserialize, Serialize}; + +use crate::schema::blocklist_fingerprint; + +#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] +#[diesel(table_name = blocklist_fingerprint)] +pub struct BlocklistFingerprintNew { + pub merchant_id: String, + pub fingerprint_id: String, + pub data_kind: common_enums::BlocklistDataKind, + pub encrypted_fingerprint: String, + pub created_at: time::PrimitiveDateTime, +} + +#[derive(Clone, Debug, Eq, PartialEq, Queryable, Identifiable, Deserialize, Serialize)] +#[diesel(table_name = blocklist_fingerprint)] +pub struct BlocklistFingerprint { + #[serde(skip_serializing)] + pub id: i32, + pub merchant_id: String, + pub fingerprint_id: String, + pub data_kind: common_enums::BlocklistDataKind, + pub encrypted_fingerprint: String, + pub created_at: time::PrimitiveDateTime, +} diff --git a/crates/diesel_models/src/blocklist_lookup.rs b/crates/diesel_models/src/blocklist_lookup.rs new file mode 100644 index 00000000000..ad2a893e03d --- /dev/null +++ b/crates/diesel_models/src/blocklist_lookup.rs @@ -0,0 +1,20 @@ +use diesel::{Identifiable, Insertable, Queryable}; +use serde::{Deserialize, Serialize}; + +use crate::schema::blocklist_lookup; + +#[derive(Default, Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)] +#[diesel(table_name = blocklist_lookup)] +pub struct BlocklistLookupNew { + pub merchant_id: String, + pub fingerprint: String, +} + +#[derive(Default, Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Deserialize, Serialize)] +#[diesel(table_name = blocklist_lookup)] +pub struct BlocklistLookup { + #[serde(skip)] + pub id: i32, + pub merchant_id: String, + pub fingerprint: String, +} diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 792e8ffc8bb..a06937c99a6 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -2,9 +2,9 @@ pub mod diesel_exports { pub use super::{ DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, - DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, - DbConnectorStatus as ConnectorStatus, DbConnectorType as ConnectorType, - DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, + DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod, + DbCaptureStatus as CaptureStatus, DbConnectorStatus as ConnectorStatus, + DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDashboardMetadata as DashboardMetadata, DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index fa32fb84a15..82b1e29ee83 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -1,11 +1,14 @@ pub mod address; pub mod api_keys; +pub mod blocklist_lookup; pub mod business_profile; pub mod capture; pub mod cards_info; pub mod configs; pub mod authorization; +pub mod blocklist; +pub mod blocklist_fingerprint; pub mod customers; pub mod dispute; pub mod encryption; diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 17784bc5659..31bc0c06c51 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -56,6 +56,7 @@ pub struct PaymentIntent { pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, + pub fingerprint_id: Option<String>, } #[derive( @@ -107,6 +108,7 @@ pub struct PaymentIntentNew { pub authorization_count: Option<i32>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub session_expiry: Option<PrimitiveDateTime>, + pub fingerprint_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -160,6 +162,7 @@ pub enum PaymentIntentUpdate { payment_confirm_source: Option<storage_enums::PaymentSource>, updated_by: String, session_expiry: Option<PrimitiveDateTime>, + fingerprint_id: Option<String>, }, PaymentAttemptAndAttemptCountUpdate { active_attempt_id: String, @@ -226,6 +229,7 @@ pub struct PaymentIntentUpdateInternal { pub incremental_authorization_allowed: Option<bool>, pub authorization_count: Option<i32>, pub session_expiry: Option<PrimitiveDateTime>, + pub fingerprint_id: Option<String>, } impl PaymentIntentUpdate { @@ -259,6 +263,7 @@ impl PaymentIntentUpdate { incremental_authorization_allowed, authorization_count, session_expiry, + fingerprint_id, } = self.into(); PaymentIntent { amount: amount.unwrap_or(source.amount), @@ -288,9 +293,11 @@ impl PaymentIntentUpdate { payment_confirm_source: payment_confirm_source.or(source.payment_confirm_source), updated_by, surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable), + incremental_authorization_allowed: incremental_authorization_allowed .or(source.incremental_authorization_allowed), authorization_count: authorization_count.or(source.authorization_count), + fingerprint_id: fingerprint_id.or(source.fingerprint_id), session_expiry: session_expiry.or(source.session_expiry), ..source } @@ -319,6 +326,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { payment_confirm_source, updated_by, session_expiry, + fingerprint_id, } => Self { amount: Some(amount), currency: Some(currency), @@ -339,6 +347,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal { payment_confirm_source, updated_by, session_expiry, + fingerprint_id, ..Default::default() }, PaymentIntentUpdate::MetadataUpdate { diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index 3a3dee47a85..3a0a008b76b 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -1,11 +1,14 @@ pub mod address; pub mod api_keys; +pub mod blocklist_lookup; pub mod business_profile; mod capture; pub mod cards_info; pub mod configs; pub mod authorization; +pub mod blocklist; +pub mod blocklist_fingerprint; pub mod customers; pub mod dashboard_metadata; pub mod dispute; diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rs new file mode 100644 index 00000000000..e1ba5fa923d --- /dev/null +++ b/crates/diesel_models/src/query/blocklist.rs @@ -0,0 +1,83 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + blocklist::{Blocklist, BlocklistNew}, + schema::blocklist::dsl, + PgPooledConn, StorageResult, +}; + +impl BlocklistNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Blocklist> { + generics::generic_insert(conn, self).await + } +} + +impl Blocklist { + #[instrument(skip(conn))] + pub async fn find_by_merchant_id_fingerprint_id( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint_id: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn list_by_merchant_id_data_kind( + conn: &PgPooledConn, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, + limit: i64, + offset: i64, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::data_kind.eq(data_kind.to_owned())), + Some(limit), + Some(offset), + Some(dsl::created_at.desc()), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn list_by_merchant_id( + conn: &PgPooledConn, + merchant_id: &str, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::merchant_id.eq(merchant_id.to_owned()), + None, + None, + Some(dsl::created_at.desc()), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn delete_by_merchant_id_fingerprint_id( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint_id: &str, + ) -> StorageResult<Self> { + generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), + ) + .await + } +} diff --git a/crates/diesel_models/src/query/blocklist_fingerprint.rs b/crates/diesel_models/src/query/blocklist_fingerprint.rs new file mode 100644 index 00000000000..4f3d77e63a8 --- /dev/null +++ b/crates/diesel_models/src/query/blocklist_fingerprint.rs @@ -0,0 +1,33 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew}, + schema::blocklist_fingerprint::dsl, + PgPooledConn, StorageResult, +}; + +impl BlocklistFingerprintNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistFingerprint> { + generics::generic_insert(conn, self).await + } +} + +impl BlocklistFingerprint { + #[instrument(skip(conn))] + pub async fn find_by_merchant_id_fingerprint_id( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint_id: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())), + ) + .await + } +} diff --git a/crates/diesel_models/src/query/blocklist_lookup.rs b/crates/diesel_models/src/query/blocklist_lookup.rs new file mode 100644 index 00000000000..ea28c94e491 --- /dev/null +++ b/crates/diesel_models/src/query/blocklist_lookup.rs @@ -0,0 +1,48 @@ +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; +use router_env::{instrument, tracing}; + +use super::generics; +use crate::{ + blocklist_lookup::{BlocklistLookup, BlocklistLookupNew}, + schema::blocklist_lookup::dsl, + PgPooledConn, StorageResult, +}; + +impl BlocklistLookupNew { + #[instrument(skip(conn))] + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistLookup> { + generics::generic_insert(conn, self).await + } +} + +impl BlocklistLookup { + #[instrument(skip(conn))] + pub async fn find_by_merchant_id_fingerprint( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint.eq(fingerprint.to_owned())), + ) + .await + } + + #[instrument(skip(conn))] + pub async fn delete_by_merchant_id_fingerprint( + conn: &PgPooledConn, + merchant_id: &str, + fingerprint: &str, + ) -> StorageResult<Self> { + generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>( + conn, + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::fingerprint.eq(fingerprint.to_owned())), + ) + .await + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index b29a362e3b0..131d2b18266 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -57,6 +57,50 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + blocklist (id) { + id -> Int4, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + fingerprint_id -> Varchar, + data_kind -> BlocklistDataKind, + metadata -> Nullable<Jsonb>, + created_at -> Timestamp, + } +} + +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + blocklist_fingerprint (id) { + id -> Int4, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + fingerprint_id -> Varchar, + data_kind -> BlocklistDataKind, + encrypted_fingerprint -> Text, + created_at -> Timestamp, + } +} + +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + blocklist_lookup (id) { + id -> Int4, + #[max_length = 64] + merchant_id -> Varchar, + fingerprint -> Text, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -709,6 +753,8 @@ diesel::table! { incremental_authorization_allowed -> Nullable<Bool>, authorization_count -> Nullable<Int4>, session_expiry -> Nullable<Timestamp>, + #[max_length = 64] + fingerprint_id -> Nullable<Varchar>, } } @@ -1016,6 +1062,9 @@ diesel::table! { diesel::allow_tables_to_appear_in_same_query!( address, api_keys, + blocklist, + blocklist_fingerprint, + blocklist_lookup, business_profile, captures, cards_info, diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 5963110c632..63205ea68ca 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -520,6 +520,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { connector_name, }, errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod, + errors::ApiErrorResponse::PaymentBlocked => Self::PaymentFailed, errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter { param: "client_secret".to_owned(), }, diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index afe76184630..ed020b0c7e0 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -27,6 +27,9 @@ pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60; /// Payment intent default client secret expiry (in seconds) pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60; +/// The length of a merchant fingerprint secret +pub const FINGERPRINT_SECRET_LENGTH: usize = 64; + // String literals pub(crate) const NO_ERROR_MESSAGE: &str = "No error message"; pub(crate) const NO_ERROR_CODE: &str = "No error code"; diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index 0bd197ee22e..5ae4b0be33d 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -1,6 +1,7 @@ pub mod admin; pub mod api_keys; pub mod api_locking; +pub mod blocklist; pub mod cache; pub mod cards_info; pub mod conditional_config; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 2577bb83a3a..e8593581126 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -10,6 +10,7 @@ use common_utils::{ ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, pii, }; +use diesel_models::configs; use error_stack::{report, FutureExt, IntoReport, ResultExt}; use futures::future::try_join_all; use masking::{PeekInterface, Secret}; @@ -141,6 +142,17 @@ pub async fn create_merchant_account( .transpose()? .map(Secret::new); + let fingerprint = Some(utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs")); + if let Some(fingerprint) = fingerprint { + db.insert_config(configs::ConfigNew { + key: format!("fingerprint_secret_{}", req.merchant_id), + config: fingerprint, + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Mot able to generate Merchant fingerprint")?; + }; + let organization_id = if let Some(organization_id) = req.organization_id.as_ref() { db.find_organization_by_org_id(organization_id) .await diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rs new file mode 100644 index 00000000000..85845602449 --- /dev/null +++ b/crates/router/src/core/blocklist.rs @@ -0,0 +1,41 @@ +pub mod transformers; +pub mod utils; + +use api_models::blocklist as api_blocklist; + +use crate::{ + core::errors::{self, RouterResponse}, + routes::AppState, + services, + types::domain, +}; + +pub async fn add_entry_to_blocklist( + state: AppState, + merchant_account: domain::MerchantAccount, + body: api_blocklist::AddToBlocklistRequest, +) -> RouterResponse<api_blocklist::AddToBlocklistResponse> { + utils::insert_entry_into_blocklist(&state, merchant_account.merchant_id, body) + .await + .map(services::ApplicationResponse::Json) +} + +pub async fn remove_entry_from_blocklist( + state: AppState, + merchant_account: domain::MerchantAccount, + body: api_blocklist::DeleteFromBlocklistRequest, +) -> RouterResponse<api_blocklist::DeleteFromBlocklistResponse> { + utils::delete_entry_from_blocklist(&state, merchant_account.merchant_id, body) + .await + .map(services::ApplicationResponse::Json) +} + +pub async fn list_blocklist_entries( + state: AppState, + merchant_account: domain::MerchantAccount, + query: api_blocklist::ListBlocklistQuery, +) -> RouterResponse<Vec<api_blocklist::BlocklistResponse>> { + utils::list_blocklist_entries_for_merchant(&state, merchant_account.merchant_id, query) + .await + .map(services::ApplicationResponse::Json) +} diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rs new file mode 100644 index 00000000000..2cb5f86a264 --- /dev/null +++ b/crates/router/src/core/blocklist/transformers.rs @@ -0,0 +1,13 @@ +use api_models::blocklist; + +use crate::types::{storage, transformers::ForeignFrom}; + +impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse { + fn foreign_from(from: storage::Blocklist) -> Self { + Self { + fingerprint_id: from.fingerprint_id, + data_kind: from.data_kind, + created_at: from.created_at, + } + } +} diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs new file mode 100644 index 00000000000..b7effaf63ac --- /dev/null +++ b/crates/router/src/core/blocklist/utils.rs @@ -0,0 +1,359 @@ +use api_models::blocklist as api_blocklist; +use common_utils::crypto::{self, SignMessage}; +use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "kms")] +use external_services::kms; + +use super::{errors, AppState}; +use crate::{ + consts, + core::errors::{RouterResult, StorageErrorExt}, + types::{storage, transformers::ForeignInto}, + utils, +}; + +pub async fn delete_entry_from_blocklist( + state: &AppState, + merchant_id: String, + request: api_blocklist::DeleteFromBlocklistRequest, +) -> RouterResult<api_blocklist::DeleteFromBlocklistResponse> { + let blocklist_entry = match request { + api_blocklist::DeleteFromBlocklistRequest::CardBin(bin) => { + delete_card_bin_blocklist_entry(state, &bin, &merchant_id).await? + } + + api_blocklist::DeleteFromBlocklistRequest::ExtendedCardBin(xbin) => { + delete_card_bin_blocklist_entry(state, &xbin, &merchant_id).await? + } + + api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => { + let blocklist_fingerprint = state + .store + .find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &merchant_id, + &fingerprint_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "blocklist record with given fingerprint id not found".to_string(), + })?; + + #[cfg(feature = "kms")] + let decrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + .await + .decrypt(blocklist_fingerprint.encrypted_fingerprint) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to kms decrypt fingerprint")?; + + #[cfg(not(feature = "kms"))] + let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; + + let blocklist_entry = state + .store + .delete_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, &fingerprint_id) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "no blocklist record for the given fingerprint id was found" + .to_string(), + })?; + + state + .store + .delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + &decrypted_fingerprint, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "no blocklist record for the given fingerprint id was found" + .to_string(), + })?; + + blocklist_entry + } + }; + + Ok(blocklist_entry.foreign_into()) +} + +pub async fn list_blocklist_entries_for_merchant( + state: &AppState, + merchant_id: String, + query: api_blocklist::ListBlocklistQuery, +) -> RouterResult<Vec<api_blocklist::BlocklistResponse>> { + state + .store + .list_blocklist_entries_by_merchant_id_data_kind( + &merchant_id, + query.data_kind, + query.limit.into(), + query.offset.into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "no blocklist records found".to_string(), + }) + .map(|v| v.into_iter().map(ForeignInto::foreign_into).collect()) +} + +fn validate_card_bin(bin: &str) -> RouterResult<()> { + if bin.len() == 6 && bin.chars().all(|c| c.is_ascii_digit()) { + Ok(()) + } else { + Err(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "data".to_string(), + expected_format: "a 6 digit number".to_string(), + }) + .into_report() + } +} + +fn validate_extended_card_bin(bin: &str) -> RouterResult<()> { + if bin.len() == 8 && bin.chars().all(|c| c.is_ascii_digit()) { + Ok(()) + } else { + Err(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "data".to_string(), + expected_format: "an 8 digit number".to_string(), + }) + .into_report() + } +} + +pub async fn insert_entry_into_blocklist( + state: &AppState, + merchant_id: String, + to_block: api_blocklist::AddToBlocklistRequest, +) -> RouterResult<api_blocklist::AddToBlocklistResponse> { + let blocklist_entry = match &to_block { + api_blocklist::AddToBlocklistRequest::CardBin(bin) => { + validate_card_bin(bin)?; + duplicate_check_insert_bin( + bin, + state, + &merchant_id, + common_enums::BlocklistDataKind::CardBin, + ) + .await? + } + + api_blocklist::AddToBlocklistRequest::ExtendedCardBin(bin) => { + validate_extended_card_bin(bin)?; + duplicate_check_insert_bin( + bin, + state, + &merchant_id, + common_enums::BlocklistDataKind::ExtendedCardBin, + ) + .await? + } + + api_blocklist::AddToBlocklistRequest::Fingerprint(fingerprint_id) => { + let blocklist_entry_result = state + .store + .find_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, fingerprint_id) + .await; + + match blocklist_entry_result { + Ok(_) => { + return Err(errors::ApiErrorResponse::PreconditionFailed { + message: "data associated with the given fingerprint is already blocked" + .to_string(), + }) + .into_report(); + } + + // if it is a db not found error, we can proceed as normal + Err(inner) if inner.current_context().is_db_not_found() => {} + + err @ Err(_) => { + err.change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error fetching blocklist entry from table")?; + } + } + + let blocklist_fingerprint = state + .store + .find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &merchant_id, + fingerprint_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "fingerprint not found".to_string(), + })?; + + #[cfg(feature = "kms")] + let decrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + .await + .decrypt(blocklist_fingerprint.encrypted_fingerprint) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to kms decrypt encrypted fingerprint")?; + + #[cfg(not(feature = "kms"))] + let decrypted_fingerprint = blocklist_fingerprint.encrypted_fingerprint; + + state + .store + .insert_blocklist_lookup_entry( + diesel_models::blocklist_lookup::BlocklistLookupNew { + merchant_id: merchant_id.clone(), + fingerprint: decrypted_fingerprint, + }, + ) + .await + .to_duplicate_response(errors::ApiErrorResponse::PreconditionFailed { + message: "the payment instrument associated with the given fingerprint is already in the blocklist".to_string(), + }) + .attach_printable("failed to add fingerprint to blocklist lookup")?; + + state + .store + .insert_blocklist_entry(storage::BlocklistNew { + merchant_id: merchant_id.clone(), + fingerprint_id: fingerprint_id.clone(), + data_kind: blocklist_fingerprint.data_kind, + metadata: None, + created_at: common_utils::date_time::now(), + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to add fingerprint to pm blocklist")? + } + }; + + Ok(blocklist_entry.foreign_into()) +} + +pub async fn get_merchant_fingerprint_secret( + state: &AppState, + merchant_id: &str, +) -> RouterResult<String> { + let key = get_merchant_fingerprint_secret_key(merchant_id); + let config_fetch_result = state.store.find_config_by_key(&key).await; + + match config_fetch_result { + Ok(config) => Ok(config.config), + + Err(e) if e.current_context().is_db_not_found() => { + let new_fingerprint_secret = + utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs"); + let new_config = storage::ConfigNew { + key, + config: new_fingerprint_secret.clone(), + }; + + state + .store + .insert_config(new_config) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to create new fingerprint secret for merchant")?; + + Ok(new_fingerprint_secret) + } + + Err(e) => Err(e) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error fetching merchant fingerprint secret"), + } +} + +pub fn get_merchant_fingerprint_secret_key(merchant_id: &str) -> String { + format!("fingerprint_secret_{merchant_id}") +} + +async fn duplicate_check_insert_bin( + bin: &str, + state: &AppState, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, +) -> RouterResult<storage::Blocklist> { + let merchant_secret = get_merchant_fingerprint_secret(state, merchant_id).await?; + let bin_fingerprint = crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_secret.clone().as_bytes(), + bin.as_bytes(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error in bin hash creation")?; + + let encoded_fingerprint = hex::encode(bin_fingerprint.clone()); + + let blocklist_entry_result = state + .store + .find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin) + .await; + + match blocklist_entry_result { + Ok(_) => { + return Err(errors::ApiErrorResponse::PreconditionFailed { + message: "provided bin is already blocked".to_string(), + }) + .into_report(); + } + + Err(e) if e.current_context().is_db_not_found() => {} + + err @ Err(_) => { + return err + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to fetch blocklist entry"); + } + } + + // Checking for duplicacy + state + .store + .insert_blocklist_lookup_entry(diesel_models::blocklist_lookup::BlocklistLookupNew { + merchant_id: merchant_id.to_string(), + fingerprint: encoded_fingerprint.clone(), + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error inserting blocklist lookup entry")?; + + state + .store + .insert_blocklist_entry(storage::BlocklistNew { + merchant_id: merchant_id.to_string(), + fingerprint_id: bin.to_string(), + data_kind, + metadata: None, + created_at: common_utils::date_time::now(), + }) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error inserting pm blocklist item") +} + +async fn delete_card_bin_blocklist_entry( + state: &AppState, + bin: &str, + merchant_id: &str, +) -> RouterResult<storage::Blocklist> { + let merchant_secret = get_merchant_fingerprint_secret(state, merchant_id).await?; + let bin_fingerprint = crypto::HmacSha512 + .sign_message(merchant_secret.as_bytes(), bin.as_bytes()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error when hashing card bin")?; + let encoded_fingerprint = hex::encode(bin_fingerprint); + + state + .store + .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, &encoded_fingerprint) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "could not find a blocklist entry for the given bin".to_string(), + })?; + + state + .store + .delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, bin) + .await + .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError { + message: "could not find a blocklist entry for the given bin".to_string(), + }) +} diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index f94504cf274..54ec4ec1e29 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -186,6 +186,8 @@ pub enum ApiErrorResponse { PaymentNotSucceeded, #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")] MerchantConnectorAccountDisabled, + #[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified payment is blocked")] + PaymentBlocked, #[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")] diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs index fa9a5185790..ff764cafed6 100644 --- a/crates/router/src/core/errors/transformers.rs +++ b/crates/router/src/core/errors/transformers.rs @@ -187,6 +187,7 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.clone()), ..Default::default() }))) } Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)), + Self::PaymentBlocked => AER::BadRequest(ApiError::new("HE", 3, "The payment is blocked", None)), Self::SuccessfulPaymentNotFound => { AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None)) } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index ec6371f310f..003c09b7381 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2586,6 +2586,7 @@ mod tests { modified_at: common_utils::date_time::now(), last_synced: None, setup_future_usage: None, + fingerprint_id: None, off_session: None, client_secret: Some("1".to_string()), active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()), @@ -2638,6 +2639,7 @@ mod tests { statement_descriptor_suffix: None, created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)), modified_at: common_utils::date_time::now(), + fingerprint_id: None, last_synced: None, setup_future_usage: None, off_session: None, @@ -2695,6 +2697,7 @@ mod tests { setup_future_usage: None, off_session: None, client_secret: None, + fingerprint_id: None, active_attempt: data_models::RemoteStorageObject::ForeignID("nopes".to_string()), business_country: None, business_label: None, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 00ae8da6ae4..c81145c5de7 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -2,23 +2,30 @@ use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; -use common_utils::ext_traits::{AsyncExt, Encode}; +use common_utils::{ + crypto::{self, SignMessage}, + ext_traits::{AsyncExt, Encode}, +}; use error_stack::{report, IntoReport, ResultExt}; +#[cfg(feature = "kms")] +use external_services::kms; use futures::FutureExt; use router_derive::PaymentOperation; -use router_env::{instrument, tracing}; +use router_env::{instrument, logger, tracing}; use tracing_futures::Instrument; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ + consts, core::{ + blocklist::utils as blocklist_utils, errors::{self, CustomResult, RouterResult, StorageErrorExt}, payment_methods::PaymentMethodRetrieve, payments::{ self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress, PaymentData, }, - utils::{self as core_utils}, + utils as core_utils, }, db::StorageInterface, routes::AppState, @@ -620,32 +627,34 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> where F: 'b + Send, { + let db = state.store.as_ref(); let payment_method = payment_data.payment_attempt.payment_method; let browser_info = payment_data.payment_attempt.browser_info.clone(); let frm_message = payment_data.frm_message.clone(); - let (intent_status, attempt_status, (error_code, error_message)) = match frm_suggestion { - Some(FrmSuggestion::FrmCancelTransaction) => ( - storage_enums::IntentStatus::Failed, - storage_enums::AttemptStatus::Failure, - frm_message.map_or((None, None), |fraud_check| { - ( - Some(Some(fraud_check.frm_status.to_string())), - Some(fraud_check.frm_reason.map(|reason| reason.to_string())), - ) - }), - ), - Some(FrmSuggestion::FrmManualReview) => ( - storage_enums::IntentStatus::RequiresMerchantAction, - storage_enums::AttemptStatus::Unresolved, - (None, None), - ), - _ => ( - storage_enums::IntentStatus::Processing, - storage_enums::AttemptStatus::Pending, - (None, None), - ), - }; + let (mut intent_status, mut attempt_status, (error_code, error_message)) = + match frm_suggestion { + Some(FrmSuggestion::FrmCancelTransaction) => ( + storage_enums::IntentStatus::Failed, + storage_enums::AttemptStatus::Failure, + frm_message.map_or((None, None), |fraud_check| { + ( + Some(Some(fraud_check.frm_status.to_string())), + Some(fraud_check.frm_reason.map(|reason| reason.to_string())), + ) + }), + ), + Some(FrmSuggestion::FrmManualReview) => ( + storage_enums::IntentStatus::RequiresMerchantAction, + storage_enums::AttemptStatus::Unresolved, + (None, None), + ), + _ => ( + storage_enums::IntentStatus::Processing, + storage_enums::AttemptStatus::Pending, + (None, None), + ), + }; let connector = payment_data.payment_attempt.connector.clone(); let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone(); @@ -709,6 +718,157 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> let m_error_message = error_message.clone(); let m_db = state.clone().store; + // Validate Blocklist + let merchant_id = payment_data.payment_attempt.merchant_id; + let merchant_fingerprint_secret = + blocklist_utils::get_merchant_fingerprint_secret(state, &merchant_id).await?; + + // Hashed Fingerprint to check whether or not this payment should be blocked. + let card_number_fingerprint = payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_fingerprint_secret.as_bytes(), + card.card_number.clone().get_card_no().as_bytes(), + ) + .attach_printable("error in pm fingerprint creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + } + _ => None, + }) + .map(hex::encode); + + // Hashed Cardbin to check whether or not this payment should be blocked. + let card_bin_fingerprint = payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_fingerprint_secret.as_bytes(), + card.card_number.clone().get_card_isin().as_bytes(), + ) + .attach_printable("error in card bin hash creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + } + _ => None, + }) + .map(hex::encode); + + // Hashed Extended Cardbin to check whether or not this payment should be blocked. + let extended_card_bin_fingerprint = payment_data + .payment_method_data + .as_ref() + .and_then(|pm_data| match pm_data { + api_models::payments::PaymentMethodData::Card(card) => { + crypto::HmacSha512::sign_message( + &crypto::HmacSha512, + merchant_fingerprint_secret.as_bytes(), + card.card_number.clone().get_extended_card_bin().as_bytes(), + ) + .attach_printable("error in extended card bin hash creation") + .map_or_else( + |err| { + logger::error!(error=?err); + None + }, + Some, + ) + } + _ => None, + }) + .map(hex::encode); + + let mut fingerprint_id = None; + + //validating the payment method. + let mut is_pm_blocklisted = false; + + let mut blocklist_futures = Vec::new(); + if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() { + blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + card_number_fingerprint, + )); + } + + if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() { + blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + card_bin_fingerprint, + )); + } + + if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() { + blocklist_futures.push(db.find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &merchant_id, + extended_card_bin_fingerprint, + )); + } + + let blocklist_lookups = futures::future::join_all(blocklist_futures).await; + + if blocklist_lookups.iter().any(|x| x.is_ok()) { + intent_status = storage_enums::IntentStatus::Failed; + attempt_status = storage_enums::AttemptStatus::Failure; + is_pm_blocklisted = true; + } + + if let Some(encoded_hash) = card_number_fingerprint { + #[cfg(feature = "kms")] + let encrypted_fingerprint = kms::get_kms_client(&state.conf.kms) + .await + .encrypt(encoded_hash) + .await + .map_or_else( + |e| { + logger::error!(error=?e, "failed kms encryption of card fingerprint"); + None + }, + Some, + ); + + #[cfg(not(feature = "kms"))] + let encrypted_fingerprint = Some(encoded_hash); + + if let Some(encrypted_fingerprint) = encrypted_fingerprint { + fingerprint_id = db + .insert_blocklist_fingerprint_entry( + diesel_models::blocklist_fingerprint::BlocklistFingerprintNew { + merchant_id, + fingerprint_id: utils::generate_id(consts::ID_LENGTH, "fingerprint"), + encrypted_fingerprint, + data_kind: common_enums::BlocklistDataKind::PaymentMethod, + created_at: common_utils::date_time::now(), + }, + ) + .await + .map_or_else( + |e| { + logger::error!(error=?e, "failed storing card fingerprint in db"); + None + }, + |fp| Some(fp.fingerprint_id), + ); + } + } + let surcharge_amount = payment_data .surcharge_details .as_ref() @@ -789,6 +949,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> metadata: m_metadata, payment_confirm_source: header_payload.payment_confirm_source, updated_by: m_storage_scheme, + fingerprint_id, session_expiry, }, storage_scheme, @@ -838,6 +999,11 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> payment_data.payment_intent = payment_intent; payment_data.payment_attempt = payment_attempt; + // Block the payment if the entry was present in the Blocklist + if is_pm_blocklisted { + return Err(errors::ApiErrorResponse::PaymentBlocked.into()); + } + Ok((Box::new(self), payment_data)) } } diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 09ec436ed00..2b25a74deb1 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -825,6 +825,7 @@ impl PaymentCreate { request_incremental_authorization, incremental_authorization_allowed: None, authorization_count: None, + fingerprint_id: None, session_expiry: Some(session_expiry), }) } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index afb83d38dc5..e002b92d181 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -617,6 +617,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve> metadata, payment_confirm_source: None, updated_by: storage_scheme.to_string(), + fingerprint_id: None, session_expiry, }, storage_scheme, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7b7d64a5f81..c3f52618f0a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -706,6 +706,7 @@ where .set_incremental_authorization_allowed( payment_intent.incremental_authorization_allowed, ) + .set_fingerprint(payment_intent.fingerprint_id) .set_authorization_count(payment_intent.authorization_count) .set_incremental_authorizations(incremental_authorizations_response) .to_owned(), diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 5beace9cbb8..b9d346b7a71 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -1,6 +1,9 @@ pub mod address; pub mod api_keys; pub mod authorization; +pub mod blocklist; +pub mod blocklist_fingerprint; +pub mod blocklist_lookup; pub mod business_profile; pub mod cache; pub mod capture; @@ -68,6 +71,7 @@ pub trait StorageInterface: + dyn_clone::DynClone + address::AddressInterface + api_keys::ApiKeyInterface + + blocklist_lookup::BlocklistLookupInterface + configs::ConfigInterface + capture::CaptureInterface + customers::CustomerInterface @@ -85,6 +89,8 @@ pub trait StorageInterface: + PaymentAttemptInterface + PaymentIntentInterface + payment_method::PaymentMethodInterface + + blocklist::BlocklistInterface + + blocklist_fingerprint::BlocklistFingerprintInterface + scheduler::SchedulerInterface + payout_attempt::PayoutAttemptInterface + payouts::PayoutsInterface diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rs new file mode 100644 index 00000000000..c263bef63c5 --- /dev/null +++ b/crates/router/src/db/blocklist.rs @@ -0,0 +1,203 @@ +use error_stack::IntoReport; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait BlocklistInterface { + async fn insert_blocklist_entry( + &self, + pm_blocklist_new: storage::BlocklistNew, + ) -> CustomResult<storage::Blocklist, errors::StorageError>; + + async fn find_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError>; + + async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError>; + + async fn list_blocklist_entries_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; + + async fn list_blocklist_entries_by_merchant_id_data_kind( + &self, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; +} + +#[async_trait::async_trait] +impl BlocklistInterface for Store { + #[instrument(skip_all)] + async fn insert_blocklist_entry( + &self, + pm_blocklist: storage::BlocklistNew, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + pm_blocklist + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + } + + async fn find_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Blocklist::find_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) + .await + .map_err(Into::into) + .into_report() + } + + async fn list_blocklist_entries_by_merchant_id( + &self, + merchant_id: &str, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Blocklist::list_by_merchant_id(&conn, merchant_id) + .await + .map_err(Into::into) + .into_report() + } + + async fn list_blocklist_entries_by_merchant_id_data_kind( + &self, + merchant_id: &str, + data_kind: common_enums::BlocklistDataKind, + limit: i64, + offset: i64, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Blocklist::list_by_merchant_id_data_kind( + &conn, + merchant_id, + data_kind, + limit, + offset, + ) + .await + .map_err(Into::into) + .into_report() + } + + async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Blocklist::delete_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl BlocklistInterface for MockDb { + #[instrument(skip_all)] + async fn insert_blocklist_entry( + &self, + _pm_blocklist: storage::BlocklistNew, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn find_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn list_blocklist_entries_by_merchant_id( + &self, + _merchant_id: &str, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn list_blocklist_entries_by_merchant_id_data_kind( + &self, + _merchant_id: &str, + _data_kind: common_enums::BlocklistDataKind, + _limit: i64, + _offset: i64, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl BlocklistInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_blocklist_entry( + &self, + _pm_blocklist: storage::BlocklistNew, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn find_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::Blocklist, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn list_blocklist_entries_by_merchant_id_data_kind( + &self, + _merchant_id: &str, + _data_kind: common_enums::BlocklistDataKind, + _limit: i64, + _offset: i64, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn list_blocklist_entries_by_merchant_id( + &self, + _merchant_id: &str, + ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } +} diff --git a/crates/router/src/db/blocklist_fingerprint.rs b/crates/router/src/db/blocklist_fingerprint.rs new file mode 100644 index 00000000000..9da7c7d8fb2 --- /dev/null +++ b/crates/router/src/db/blocklist_fingerprint.rs @@ -0,0 +1,95 @@ +use error_stack::IntoReport; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait BlocklistFingerprintInterface { + async fn insert_blocklist_fingerprint_entry( + &self, + pm_fingerprint_new: storage::BlocklistFingerprintNew, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; + + async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; +} + +#[async_trait::async_trait] +impl BlocklistFingerprintInterface for Store { + #[instrument(skip_all)] + async fn insert_blocklist_fingerprint_entry( + &self, + pm_fingerprint_new: storage::BlocklistFingerprintNew, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + pm_fingerprint_new + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + } + + async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &self, + merchant_id: &str, + fingerprint_id: &str, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::BlocklistFingerprint::find_by_merchant_id_fingerprint_id( + &conn, + merchant_id, + fingerprint_id, + ) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl BlocklistFingerprintInterface for MockDb { + #[instrument(skip_all)] + async fn insert_blocklist_fingerprint_entry( + &self, + _pm_fingerprint_new: storage::BlocklistFingerprintNew, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl BlocklistFingerprintInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_blocklist_fingerprint_entry( + &self, + _pm_fingerprint_new: storage::BlocklistFingerprintNew, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( + &self, + _merchant_id: &str, + _fingerprint_id: &str, + ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } +} diff --git a/crates/router/src/db/blocklist_lookup.rs b/crates/router/src/db/blocklist_lookup.rs new file mode 100644 index 00000000000..0dfd81c8b8a --- /dev/null +++ b/crates/router/src/db/blocklist_lookup.rs @@ -0,0 +1,125 @@ +use error_stack::IntoReport; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait BlocklistLookupInterface { + async fn insert_blocklist_lookup_entry( + &self, + blocklist_lookup_new: storage::BlocklistLookupNew, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; + + async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + merchant_id: &str, + fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; + + async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + merchant_id: &str, + fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; +} + +#[async_trait::async_trait] +impl BlocklistLookupInterface for Store { + #[instrument(skip_all)] + async fn insert_blocklist_lookup_entry( + &self, + blocklist_lookup_entry: storage::BlocklistLookupNew, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + blocklist_lookup_entry + .insert(&conn) + .await + .map_err(Into::into) + .into_report() + } + + async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + merchant_id: &str, + fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::BlocklistLookup::find_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) + .await + .map_err(Into::into) + .into_report() + } + + async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + merchant_id: &str, + fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::BlocklistLookup::delete_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) + .await + .map_err(Into::into) + .into_report() + } +} + +#[async_trait::async_trait] +impl BlocklistLookupInterface for MockDb { + #[instrument(skip_all)] + async fn insert_blocklist_lookup_entry( + &self, + _blocklist_lookup_entry: storage::BlocklistLookupNew, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + _merchant_id: &str, + _fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + _merchant_id: &str, + _fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl BlocklistLookupInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_blocklist_lookup_entry( + &self, + _blocklist_lookup_entry: storage::BlocklistLookupNew, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + _merchant_id: &str, + _fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } + + async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( + &self, + _merchant_id: &str, + _fingerprint: &str, + ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { + Err(errors::StorageError::KafkaError)? + } +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 3b4c7ce9b7d..696198f2153 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -129,9 +129,9 @@ pub fn mk_app( #[cfg(feature = "oltp")] { server_app = server_app - .service(routes::PaymentMethods::server(state.clone())) .service(routes::EphemeralKey::server(state.clone())) .service(routes::Webhooks::server(state.clone())) + .service(routes::PaymentMethods::server(state.clone())) } #[cfg(feature = "olap")] @@ -143,6 +143,7 @@ pub fn mk_app( .service(routes::Disputes::server(state.clone())) .service(routes::Analytics::server(state.clone())) .service(routes::Routing::server(state.clone())) + .service(routes::Blocklist::server(state.clone())) .service(routes::LockerMigrate::server(state.clone())) .service(routes::Gsm::server(state.clone())) .service(routes::PaymentLink::server(state.clone())) diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index ec718b2dde9..d4bfabb6f92 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -1,6 +1,8 @@ pub mod admin; pub mod api_keys; pub mod app; +#[cfg(feature = "olap")] +pub mod blocklist; pub mod cache; pub mod cards_info; pub mod configs; @@ -42,14 +44,15 @@ pub mod webhooks; pub mod locker_migration; #[cfg(any(feature = "olap", feature = "oltp"))] pub mod pm_auth; +#[cfg(feature = "olap")] +pub use app::{Blocklist, Routing}; + #[cfg(feature = "dummy_connector")] pub use self::app::DummyConnector; #[cfg(any(feature = "olap", feature = "oltp"))] pub use self::app::Forex; #[cfg(feature = "payouts")] pub use self::app::Payouts; -#[cfg(feature = "olap")] -pub use self::app::Routing; #[cfg(all(feature = "olap", feature = "kms"))] pub use self::app::Verify; pub use self::app::{ diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6625a206be2..0efe2218a9a 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -14,6 +14,8 @@ use scheduler::SchedulerInterface; use storage_impl::MockDb; use tokio::sync::oneshot; +#[cfg(feature = "olap")] +use super::blocklist; #[cfg(any(feature = "olap", feature = "oltp"))] use super::currency; #[cfg(feature = "dummy_connector")] @@ -566,6 +568,23 @@ impl PaymentMethods { } } +#[cfg(feature = "olap")] +pub struct Blocklist; + +#[cfg(feature = "olap")] +impl Blocklist { + pub fn server(state: AppState) -> Scope { + web::scope("/blocklist") + .app_data(web::Data::new(state)) + .service( + web::resource("") + .route(web::get().to(blocklist::list_blocked_payment_methods)) + .route(web::post().to(blocklist::add_entry_to_blocklist)) + .route(web::delete().to(blocklist::remove_entry_from_blocklist)), + ) + } +} + pub struct MerchantAccount; #[cfg(feature = "olap")] diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs new file mode 100644 index 00000000000..7c268dddeec --- /dev/null +++ b/crates/router/src/routes/blocklist.rs @@ -0,0 +1,81 @@ +use actix_web::{web, HttpRequest, HttpResponse}; +use api_models::blocklist as api_blocklist; +use router_env::Flow; + +use crate::{ + core::{api_locking, blocklist}, + routes::AppState, + services::{api, authentication as auth, authorization::permissions::Permission}, +}; + +pub async fn add_entry_to_blocklist( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_blocklist::AddToBlocklistRequest>, +) -> HttpResponse { + let flow = Flow::AddToBlocklist; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, body| { + blocklist::add_entry_to_blocklist(state, auth.merchant_account, body) + }, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::MerchantAccountWrite), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn remove_entry_from_blocklist( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_blocklist::DeleteFromBlocklistRequest>, +) -> HttpResponse { + let flow = Flow::DeleteFromBlocklist; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, auth: auth::AuthenticationData, body| { + blocklist::remove_entry_from_blocklist(state, auth.merchant_account, body) + }, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::MerchantAccountWrite), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +pub async fn list_blocked_payment_methods( + state: web::Data<AppState>, + req: HttpRequest, + query_payload: web::Query<api_blocklist::ListBlocklistQuery>, +) -> HttpResponse { + let flow = Flow::ListBlocklist; + Box::pin(api::server_wrap( + flow, + state, + &req, + query_payload.into_inner(), + |state, auth: auth::AuthenticationData, query| { + blocklist::list_blocklist_entries(state, auth.merchant_account, query) + }, + auth::auth_type( + &auth::ApiKeyAuth, + &auth::JWTAuth(Permission::MerchantAccountRead), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 10f408f3d4f..55c6cbc23d7 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -24,6 +24,7 @@ pub enum ApiIdentifier { ApiKeys, PaymentLink, Routing, + Blocklist, Forex, RustLockerMigration, Gsm, @@ -57,6 +58,10 @@ impl From<Flow> for ApiIdentifier { Flow::RetrieveForexFlow => Self::Forex, + Flow::AddToBlocklist => Self::Blocklist, + Flow::DeleteFromBlocklist => Self::Blocklist, + Flow::ListBlocklist => Self::Blocklist, + Flow::MerchantConnectorsCreate | Flow::MerchantConnectorsRetrieve | Flow::MerchantConnectorsUpdate diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 56d3272b947..b93cbbbbba9 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -1,6 +1,9 @@ pub mod address; pub mod api_keys; pub mod authorization; +pub mod blocklist; +pub mod blocklist_fingerprint; +pub mod blocklist_lookup; pub mod business_profile; pub mod capture; pub mod cards_info; @@ -43,7 +46,8 @@ pub use diesel_models::{ProcessTracker, ProcessTrackerNew, ProcessTrackerUpdate} pub use scheduler::db::process_tracker; pub use self::{ - address::*, api_keys::*, authorization::*, capture::*, cards_info::*, configs::*, customers::*, + address::*, api_keys::*, authorization::*, blocklist::*, blocklist_fingerprint::*, + blocklist_lookup::*, capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*, ephemeral_key::*, events::*, file::*, fraud_check::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*, payout_attempt::*, payouts::*, diff --git a/crates/router/src/types/storage/blocklist.rs b/crates/router/src/types/storage/blocklist.rs new file mode 100644 index 00000000000..7e7648dd4a0 --- /dev/null +++ b/crates/router/src/types/storage/blocklist.rs @@ -0,0 +1 @@ +pub use diesel_models::blocklist::{Blocklist, BlocklistNew}; diff --git a/crates/router/src/types/storage/blocklist_fingerprint.rs b/crates/router/src/types/storage/blocklist_fingerprint.rs new file mode 100644 index 00000000000..092d881e3fa --- /dev/null +++ b/crates/router/src/types/storage/blocklist_fingerprint.rs @@ -0,0 +1 @@ +pub use diesel_models::blocklist_fingerprint::{BlocklistFingerprint, BlocklistFingerprintNew}; diff --git a/crates/router/src/types/storage/blocklist_lookup.rs b/crates/router/src/types/storage/blocklist_lookup.rs new file mode 100644 index 00000000000..978708ff7c3 --- /dev/null +++ b/crates/router/src/types/storage/blocklist_lookup.rs @@ -0,0 +1 @@ +pub use diesel_models::blocklist_lookup::{BlocklistLookup, BlocklistLookupNew}; diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 33f1e211534..dcf635595e0 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -199,6 +199,7 @@ pub async fn generate_sample_data( request_incremental_authorization: Default::default(), incremental_authorization_allowed: Default::default(), authorization_count: Default::default(), + fingerprint_id: None, session_expiry: Some(session_expiry), }; let payment_attempt = PaymentAttemptBatchNew { diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index e37e15443bd..a6ac1b1e0a1 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -185,6 +185,12 @@ pub enum Flow { RoutingUpdateDefaultConfig, /// Routing delete config RoutingDeleteConfig, + /// Add record to blocklist + AddToBlocklist, + /// Delete record from blocklist + DeleteFromBlocklist, + /// List entries from blocklist + ListBlocklist, /// Incoming Webhook Receive IncomingWebhookReceive, /// Validate payment method flow diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs index 50173bb1c73..ac3a04e85b2 100644 --- a/crates/storage_impl/src/errors.rs +++ b/crates/storage_impl/src/errors.rs @@ -55,6 +55,8 @@ pub enum StorageError { SerializationFailed, #[error("MockDb error")] MockDbError, + #[error("Kafka error")] + KafkaError, #[error("Customer with this id is Redacted")] CustomerRedacted, #[error("Deserialization failure")] @@ -103,6 +105,7 @@ impl Into<DataStorageError> for &StorageError { StorageError::KVError => DataStorageError::KVError, StorageError::SerializationFailed => DataStorageError::SerializationFailed, StorageError::MockDbError => DataStorageError::MockDbError, + StorageError::KafkaError => DataStorageError::KafkaError, StorageError::CustomerRedacted => DataStorageError::CustomerRedacted, StorageError::DeserializationFailed => DataStorageError::DeserializationFailed, StorageError::EncryptionError => DataStorageError::EncryptionError, diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index ee8676106f1..3f892ed9fa7 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -109,6 +109,7 @@ impl PaymentIntentInterface for MockDb { request_incremental_authorization: new.request_incremental_authorization, incremental_authorization_allowed: new.incremental_authorization_allowed, authorization_count: new.authorization_count, + fingerprint_id: new.fingerprint_id, session_expiry: new.session_expiry, }; payment_intents.push(payment_intent.clone()); diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 07d70c9056b..8d20dfe0f32 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -101,6 +101,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { request_incremental_authorization: new.request_incremental_authorization, incremental_authorization_allowed: new.incremental_authorization_allowed, authorization_count: new.authorization_count, + fingerprint_id: new.fingerprint_id.clone(), session_expiry: new.session_expiry, }; let redis_entry = kv::TypedSql { @@ -769,6 +770,7 @@ impl DataModelExt for PaymentIntentNew { request_incremental_authorization: self.request_incremental_authorization, incremental_authorization_allowed: self.incremental_authorization_allowed, authorization_count: self.authorization_count, + fingerprint_id: self.fingerprint_id, session_expiry: self.session_expiry, } } @@ -813,6 +815,7 @@ impl DataModelExt for PaymentIntentNew { request_incremental_authorization: storage_model.request_incremental_authorization, incremental_authorization_allowed: storage_model.incremental_authorization_allowed, authorization_count: storage_model.authorization_count, + fingerprint_id: storage_model.fingerprint_id, session_expiry: storage_model.session_expiry, } } @@ -862,6 +865,7 @@ impl DataModelExt for PaymentIntent { request_incremental_authorization: self.request_incremental_authorization, incremental_authorization_allowed: self.incremental_authorization_allowed, authorization_count: self.authorization_count, + fingerprint_id: self.fingerprint_id, session_expiry: self.session_expiry, } } @@ -907,6 +911,7 @@ impl DataModelExt for PaymentIntent { request_incremental_authorization: storage_model.request_incremental_authorization, incremental_authorization_allowed: storage_model.incremental_authorization_allowed, authorization_count: storage_model.authorization_count, + fingerprint_id: storage_model.fingerprint_id, session_expiry: storage_model.session_expiry, } } @@ -990,6 +995,7 @@ impl DataModelExt for PaymentIntentUpdate { metadata, payment_confirm_source, updated_by, + fingerprint_id, session_expiry, } => DieselPaymentIntentUpdate::Update { amount, @@ -1009,6 +1015,7 @@ impl DataModelExt for PaymentIntentUpdate { metadata, payment_confirm_source, updated_by, + fingerprint_id, session_expiry, }, Self::PaymentAttemptAndAttemptCountUpdate { diff --git a/migrations/2023-12-11-075542_create_pm_fingerprint_table/down.sql b/migrations/2023-12-11-075542_create_pm_fingerprint_table/down.sql new file mode 100644 index 00000000000..74c450622a7 --- /dev/null +++ b/migrations/2023-12-11-075542_create_pm_fingerprint_table/down.sql @@ -0,0 +1,5 @@ +-- This file should undo anything in `up.sql` + +DROP TABLE blocklist_fingerprint; + +DROP TYPE "BlocklistDataKind"; diff --git a/migrations/2023-12-11-075542_create_pm_fingerprint_table/up.sql b/migrations/2023-12-11-075542_create_pm_fingerprint_table/up.sql new file mode 100644 index 00000000000..417d779200f --- /dev/null +++ b/migrations/2023-12-11-075542_create_pm_fingerprint_table/up.sql @@ -0,0 +1,19 @@ +-- Your SQL goes here + +CREATE TYPE "BlocklistDataKind" AS ENUM ( + 'payment_method', + 'card_bin', + 'extended_card_bin' +); + +CREATE TABLE blocklist_fingerprint ( + id SERIAL PRIMARY KEY, + merchant_id VARCHAR(64) NOT NULL, + fingerprint_id VARCHAR(64) NOT NULL, + data_kind "BlocklistDataKind" NOT NULL, + encrypted_fingerprint TEXT NOT NULL, + created_at TIMESTAMP NOT NULL +); + +CREATE UNIQUE INDEX blocklist_fingerprint_merchant_id_fingerprint_id_index +ON blocklist_fingerprint (merchant_id, fingerprint_id); diff --git a/migrations/2023-12-12-112941_create_pm_blocklist_table/down.sql b/migrations/2023-12-12-112941_create_pm_blocklist_table/down.sql new file mode 100644 index 00000000000..cd7d412aad9 --- /dev/null +++ b/migrations/2023-12-12-112941_create_pm_blocklist_table/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +DROP TABLE blocklist; diff --git a/migrations/2023-12-12-112941_create_pm_blocklist_table/up.sql b/migrations/2023-12-12-112941_create_pm_blocklist_table/up.sql new file mode 100644 index 00000000000..6d921dd78c3 --- /dev/null +++ b/migrations/2023-12-12-112941_create_pm_blocklist_table/up.sql @@ -0,0 +1,13 @@ +-- Your SQL goes here + +CREATE TABLE blocklist ( + id SERIAL PRIMARY KEY, + merchant_id VARCHAR(64) NOT NULL, + fingerprint_id VARCHAR(64) NOT NULL, + data_kind "BlocklistDataKind" NOT NULL, + metadata JSONB, + created_at TIMESTAMP NOT NULL +); + +CREATE UNIQUE INDEX blocklist_unique_fingerprint_id_index ON blocklist (merchant_id, fingerprint_id); +CREATE INDEX blocklist_merchant_id_data_kind_created_at_index ON blocklist (merchant_id, data_kind, created_at DESC); diff --git a/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/down.sql b/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/down.sql new file mode 100644 index 00000000000..46b871b6ee4 --- /dev/null +++ b/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE payment_intent DROP COLUMN IF EXISTS fingerprint_id; diff --git a/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/up.sql b/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/up.sql new file mode 100644 index 00000000000..831fb7b6ffc --- /dev/null +++ b/migrations/2023-12-12-113330_add_fingerprint_id_in_payment_intent/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS fingerprint_id VARCHAR(64); diff --git a/migrations/2023-12-18-062613_create_blocklist_lookup_table/down.sql b/migrations/2023-12-18-062613_create_blocklist_lookup_table/down.sql new file mode 100644 index 00000000000..d2363f547a5 --- /dev/null +++ b/migrations/2023-12-18-062613_create_blocklist_lookup_table/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` + +DROP TABLE blocklist_lookup; diff --git a/migrations/2023-12-18-062613_create_blocklist_lookup_table/up.sql b/migrations/2023-12-18-062613_create_blocklist_lookup_table/up.sql new file mode 100644 index 00000000000..8af3e209fc6 --- /dev/null +++ b/migrations/2023-12-18-062613_create_blocklist_lookup_table/up.sql @@ -0,0 +1,9 @@ +-- Your SQL goes here + +CREATE TABLE blocklist_lookup ( + id SERIAL PRIMARY KEY, + merchant_id VARCHAR(64) NOT NULL, + fingerprint TEXT NOT NULL +); + +CREATE UNIQUE INDEX blocklist_lookup_merchant_id_fingerprint_index ON blocklist_lookup (merchant_id, fingerprint); diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index dd27b5d609d..74cfc752c57 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -10744,6 +10744,11 @@ }, "description": "List of incremental authorizations happened to the payment", "nullable": true + }, + "fingerprint": { + "type": "string", + "description": "Payment Fingerprint", + "nullable": true } } },
2023-12-05T11:57:03Z
## Description <!-- Describe your changes in detail --> This feature will allow the merchants to block the following according to their needs: ``` 1. card_numbers 2. card_isins 3. extended_bins ``` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Requested by Merchant. #
8626bda6d5aa9e7531edc7ea50ed4f30c3b7227a
Refer to the attached postman collection for the API contracts for the blocklist APIs. Currently we support blocking three types of resources i.e. card numbers (payment intrument), card bin, and extended card bin. For Card Bin and Extended Card Bin :- 1. Setup a Merchant Account and any Connector account 2. Make a payment with a certain card (ensure it succeeds) 3. Block the card's card bin or extended card bin 4. Try the payment again (should fail this time with an API response saying that the payment was blocked) For Payment Instrument :- 1. Repeat steps 1 and 2 of previous section 2. In the payment confirm response, there will be an additional field called "fingerprint". This is the fingerprint id that can be used to block a particular payment method. Use this to block the card. 3. Try the payment again (should fail) [blocklist_api_postman.zip](https://github.com/juspay/hyperswitch/files/13893696/blocklist_api_postman.zip)
[ "crates/api_models/src/blocklist.rs", "crates/api_models/src/lib.rs", "crates/api_models/src/payments.rs", "crates/cards/src/validate.rs", "crates/common_enums/src/enums.rs", "crates/data_models/src/errors.rs", "crates/data_models/src/payments.rs", "crates/data_models/src/payments/payment_intent.rs", ...
juspay/hyperswitch
juspay__hyperswitch-3046
Bug: [FEATURE] Migrate PaymentMethodAuth to OSS ### Feature Description Migrating PM auth services to OSS ### Possible Implementation Migration of PM auth crate and dependent changes ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index d2e8d9dd5df..307a5ca2398 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -405,6 +405,8 @@ dependencies = [ "common_utils", "error-stack", "euclid", + "frunk", + "frunk_core", "masking", "mime", "reqwest", @@ -4436,6 +4438,27 @@ dependencies = [ "plotters-backend", ] +[[package]] +name = "pm_auth" +version = "0.1.0" +dependencies = [ + "api_models", + "async-trait", + "bytes 1.5.0", + "common_enums", + "common_utils", + "error-stack", + "http", + "masking", + "mime", + "router_derive", + "router_env", + "serde", + "serde_json", + "strum 0.24.1", + "thiserror", +] + [[package]] name = "png" version = "0.16.8" @@ -5110,6 +5133,7 @@ dependencies = [ "num_cpus", "once_cell", "openssl", + "pm_auth", "qrcode", "rand 0.8.5", "rand_chacha 0.3.1", diff --git a/config/config.example.toml b/config/config.example.toml index 1897c935581..7a50c23f484 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -122,7 +122,7 @@ kms_encrypted_recon_admin_api_key = "" # Base64-encoded (KMS encrypted) cipher # like card details [locker] host = "" # Locker host -host_rs = "" # Rust Locker host +host_rs = "" # Rust Locker host mock_locker = true # Emulate a locker locally using Postgres basilisk_host = "" # Basilisk host locker_signing_key_id = "1" # Key_id to sign basilisk hs locker @@ -461,6 +461,10 @@ apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" #Private key [payment_link] sdk_url = "http://localhost:9090/dist/HyperLoader.js" +[payment_method_auth] +redis_expiry = 900 +pm_auth_key = "Some_pm_auth_key" + # Analytics configuration. [analytics] source = "sqlx" # The Analytics source/strategy to be used diff --git a/config/development.toml b/config/development.toml index 4ee33795676..15acfdee9b7 100644 --- a/config/development.toml +++ b/config/development.toml @@ -470,6 +470,10 @@ apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY" [payment_link] sdk_url = "http://localhost:9090/dist/HyperLoader.js" +[payment_method_auth] +redis_expiry = 900 +pm_auth_key = "Some_pm_auth_key" + [lock_settings] redis_lock_expiry_seconds = 180 # 3 * 60 seconds delay_between_retries_in_milliseconds = 500 diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 55fc62329d4..5eec8d733d6 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -330,6 +330,10 @@ payout_connector_list = "wise" [multiple_api_version_supported_connectors] supported_connectors = "braintree" +[payment_method_auth] +redis_expiry = 900 +pm_auth_key = "Some_pm_auth_key" + [lock_settings] redis_lock_expiry_seconds = 180 # 3 * 60 seconds delay_between_retries_in_milliseconds = 500 diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 116aad25d5c..afba129b601 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -30,6 +30,8 @@ strum = { version = "0.25", features = ["derive"] } time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] } url = { version = "2.4.0", features = ["serde"] } utoipa = { version = "3.3.0", features = ["preserve_order"] } +frunk = "0.4.1" +frunk_core = "0.4.1" # First party crates cards = { version = "0.1.0", path = "../cards" } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 17787929a46..21586054055 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + pub use common_enums::*; use utoipa::ToSchema; @@ -500,3 +502,26 @@ pub enum LockerChoice { Basilisk, Tartarus, } + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, + frunk::LabelledGeneric, + ToSchema, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum PmAuthConnectors { + Plaid, +} + +pub fn convert_pm_auth_connector(connector_name: &str) -> Option<PmAuthConnectors> { + PmAuthConnectors::from_str(connector_name).ok() +} diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index ce3c11d9c2f..935944cf74c 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -23,6 +23,7 @@ pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; +pub mod pm_auth; pub mod refunds; pub mod routing; pub mod surcharge_decision_configs; diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs new file mode 100644 index 00000000000..7044bd8d335 --- /dev/null +++ b/crates/api_models/src/pm_auth.rs @@ -0,0 +1,57 @@ +use common_enums::{PaymentMethod, PaymentMethodType}; +use common_utils::{ + events::{ApiEventMetric, ApiEventsType}, + impl_misc_api_event_type, +}; + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct LinkTokenCreateRequest { + pub language: Option<String>, // optional language field to be passed + pub client_secret: Option<String>, // client secret to be passed in req body + pub payment_id: String, // payment_id to be passed in req body for redis pm_auth connector name fetch + pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector + pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct LinkTokenCreateResponse { + pub link_token: String, // link_token received in response + pub connector: String, // pm_auth connector name in response +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] + +pub struct ExchangeTokenCreateRequest { + pub public_token: String, + pub client_secret: Option<String>, + pub payment_id: String, + pub payment_method: PaymentMethod, + pub payment_method_type: PaymentMethodType, +} + +#[derive(Debug, Clone, serde::Serialize)] +pub struct ExchangeTokenCreateResponse { + pub access_token: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentMethodAuthConfig { + pub enabled_payment_methods: Vec<PaymentMethodAuthConnectorChoice>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentMethodAuthConnectorChoice { + pub payment_method: PaymentMethod, + pub payment_method_type: PaymentMethodType, + pub connector_name: String, + pub mca_id: String, +} + +impl_misc_api_event_type!( + LinkTokenCreateRequest, + LinkTokenCreateResponse, + ExchangeTokenCreateRequest, + ExchangeTokenCreateResponse +); diff --git a/crates/pm_auth/Cargo.toml b/crates/pm_auth/Cargo.toml new file mode 100644 index 00000000000..a9aebc5b540 --- /dev/null +++ b/crates/pm_auth/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "pm_auth" +description = "Open banking services" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +readme = "README.md" + +[dependencies] +# First party crates +api_models = { version = "0.1.0", path = "../api_models" } +common_enums = { version = "0.1.0", path = "../common_enums" } +common_utils = { version = "0.1.0", path = "../common_utils" } +masking = { version = "0.1.0", path = "../masking" } +router_derive = { version = "0.1.0", path = "../router_derive" } +router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } + +# Third party crates +async-trait = "0.1.66" +bytes = "1.4.0" +error-stack = "0.3.1" +http = "0.2.9" +mime = "0.3.17" +serde = "1.0.159" +serde_json = "1.0.91" +strum = { version = "0.24.1", features = ["derive"] } +thiserror = "1.0.43" diff --git a/crates/pm_auth/README.md b/crates/pm_auth/README.md new file mode 100644 index 00000000000..c630a7fe676 --- /dev/null +++ b/crates/pm_auth/README.md @@ -0,0 +1,3 @@ +# Payment Method Auth Services + +An open banking services for payment method auth validation diff --git a/crates/pm_auth/src/connector.rs b/crates/pm_auth/src/connector.rs new file mode 100644 index 00000000000..56aad846e24 --- /dev/null +++ b/crates/pm_auth/src/connector.rs @@ -0,0 +1,3 @@ +pub mod plaid; + +pub use self::plaid::Plaid; diff --git a/crates/pm_auth/src/connector/plaid.rs b/crates/pm_auth/src/connector/plaid.rs new file mode 100644 index 00000000000..d25aba881d2 --- /dev/null +++ b/crates/pm_auth/src/connector/plaid.rs @@ -0,0 +1,353 @@ +pub mod transformers; + +use std::fmt::Debug; + +use common_utils::{ + ext_traits::{BytesExt, Encode}, + request::{Method, Request, RequestBody, RequestBuilder}, +}; +use error_stack::ResultExt; +use masking::{Mask, Maskable}; +use transformers as plaid; + +use crate::{ + core::errors, + types::{ + self as auth_types, + api::{ + auth_service::{self, BankAccountCredentials, ExchangeToken, LinkToken}, + ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, + }, + }, +}; + +#[derive(Debug, Clone)] +pub struct Plaid; + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid +where + Self: ConnectorIntegration<Flow, Request, Response>, +{ + fn build_headers( + &self, + req: &auth_types::PaymentAuthRouterData<Flow, Request, Response>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + let mut header = vec![( + "Content-Type".to_string(), + self.get_content_type().to_string().into(), + )]; + + let mut auth = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut auth); + Ok(header) + } +} + +impl ConnectorCommon for Plaid { + fn id(&self) -> &'static str { + "plaid" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + fn base_url<'a>(&self, _connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str { + "https://sandbox.plaid.com" + } + + fn get_auth_header( + &self, + auth_type: &auth_types::ConnectorAuthType, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + let auth = plaid::PlaidAuthType::try_from(auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let client_id = auth.client_id.into_masked(); + let secret = auth.secret.into_masked(); + + Ok(vec![ + ("PLAID-CLIENT-ID".to_string(), client_id), + ("PLAID-SECRET".to_string(), secret), + ]) + } + + fn build_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + let response: plaid::PlaidErrorResponse = + res.response + .parse_struct("PlaidErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(auth_types::ErrorResponse { + status_code: res.status_code, + code: crate::consts::NO_ERROR_CODE.to_string(), + message: response.error_message, + reason: response.display_message, + }) + } +} + +impl auth_service::AuthService for Plaid {} +impl auth_service::AuthServiceLinkToken for Plaid {} + +impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse> + for Plaid +{ + fn get_headers( + &self, + req: &auth_types::LinkTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &auth_types::LinkTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "/link/token/create" + )) + } + + fn get_request_body( + &self, + req: &auth_types::LinkTokenRouterData, + ) -> errors::CustomResult<Option<RequestBody>, errors::ConnectorError> { + let req_obj = plaid::PlaidLinkTokenRequest::try_from(req)?; + let plaid_req = RequestBody::log_and_get_request_body( + &req_obj, + Encode::<plaid::PlaidLinkTokenRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(plaid_req)) + } + + fn build_request( + &self, + req: &auth_types::LinkTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&auth_types::PaymentAuthLinkTokenType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(auth_types::PaymentAuthLinkTokenType::get_headers( + self, req, connectors, + )?) + .body(auth_types::PaymentAuthLinkTokenType::get_request_body( + self, req, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &auth_types::LinkTokenRouterData, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::LinkTokenRouterData, errors::ConnectorError> { + let response: plaid::PlaidLinkTokenResponse = res + .response + .parse_struct("PlaidLinkTokenResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + <auth_types::LinkTokenRouterData>::try_from(auth_types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl auth_service::AuthServiceExchangeToken for Plaid {} + +impl + ConnectorIntegration< + ExchangeToken, + auth_types::ExchangeTokenRequest, + auth_types::ExchangeTokenResponse, + > for Plaid +{ + fn get_headers( + &self, + req: &auth_types::ExchangeTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &auth_types::ExchangeTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}{}", + self.base_url(connectors), + "/item/public_token/exchange" + )) + } + + fn get_request_body( + &self, + req: &auth_types::ExchangeTokenRouterData, + ) -> errors::CustomResult<Option<RequestBody>, errors::ConnectorError> { + let req_obj = plaid::PlaidExchangeTokenRequest::try_from(req)?; + let plaid_req = RequestBody::log_and_get_request_body( + &req_obj, + Encode::<plaid::PlaidExchangeTokenRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(plaid_req)) + } + + fn build_request( + &self, + req: &auth_types::ExchangeTokenRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&auth_types::PaymentAuthExchangeTokenType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(auth_types::PaymentAuthExchangeTokenType::get_headers( + self, req, connectors, + )?) + .body(auth_types::PaymentAuthExchangeTokenType::get_request_body( + self, req, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &auth_types::ExchangeTokenRouterData, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ExchangeTokenRouterData, errors::ConnectorError> { + let response: plaid::PlaidExchangeTokenResponse = res + .response + .parse_struct("PlaidExchangeTokenResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + <auth_types::ExchangeTokenRouterData>::try_from(auth_types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} + +impl auth_service::AuthServiceBankAccountCredentials for Plaid {} + +impl + ConnectorIntegration< + BankAccountCredentials, + auth_types::BankAccountCredentialsRequest, + auth_types::BankAccountCredentialsResponse, + > for Plaid +{ + fn get_headers( + &self, + req: &auth_types::BankDetailsRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &auth_types::BankDetailsRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<String, errors::ConnectorError> { + Ok(format!("{}{}", self.base_url(connectors), "/auth/get")) + } + + fn get_request_body( + &self, + req: &auth_types::BankDetailsRouterData, + ) -> errors::CustomResult<Option<RequestBody>, errors::ConnectorError> { + let req_obj = plaid::PlaidBankAccountCredentialsRequest::try_from(req)?; + let plaid_req = RequestBody::log_and_get_request_body( + &req_obj, + Encode::<plaid::PlaidBankAccountCredentialsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(plaid_req)) + } + + fn build_request( + &self, + req: &auth_types::BankDetailsRouterData, + connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&auth_types::PaymentAuthBankAccountDetailsType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(auth_types::PaymentAuthBankAccountDetailsType::get_headers( + self, req, connectors, + )?) + .body(auth_types::PaymentAuthBankAccountDetailsType::get_request_body(self, req)?) + .build(), + )) + } + + fn handle_response( + &self, + data: &auth_types::BankDetailsRouterData, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::BankDetailsRouterData, errors::ConnectorError> { + let response: plaid::PlaidBankAccountCredentialsResponse = res + .response + .parse_struct("PlaidBankAccountCredentialsResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + <auth_types::BankDetailsRouterData>::try_from(auth_types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + fn get_error_response( + &self, + res: auth_types::Response, + ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { + self.build_error_response(res) + } +} diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs new file mode 100644 index 00000000000..5e1ad67aead --- /dev/null +++ b/crates/pm_auth/src/connector/plaid/transformers.rs @@ -0,0 +1,294 @@ +use std::collections::HashMap; + +use common_enums::PaymentMethodType; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{core::errors, types}; + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidLinkTokenRequest { + client_name: String, + country_codes: Vec<String>, + language: String, + products: Vec<String>, + user: User, +} + +#[derive(Debug, Serialize, Eq, PartialEq)] + +pub struct User { + pub client_user_id: String, +} + +impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::LinkTokenRouterData) -> Result<Self, Self::Error> { + Ok(Self { + client_name: item.request.client_name.clone(), + country_codes: item.request.country_codes.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "country_codes", + }, + )?, + language: item.request.language.clone().unwrap_or("en".to_string()), + products: vec!["auth".to_string()], + user: User { + client_user_id: item.request.user_info.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "country_codes", + }, + )?, + }, + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidLinkTokenResponse { + link_token: String, +} + +impl<F, T> + TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>> + for types::PaymentAuthRouterData<F, T, types::LinkTokenResponse> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::LinkTokenResponse { + link_token: item.response.link_token, + }), + ..item.data + }) + } +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidExchangeTokenRequest { + public_token: String, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] + +pub struct PlaidExchangeTokenResponse { + pub access_token: String, +} + +impl<F, T> + TryFrom< + types::ResponseRouterData<F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse>, + > for types::PaymentAuthRouterData<F, T, types::ExchangeTokenResponse> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PlaidExchangeTokenResponse, + T, + types::ExchangeTokenResponse, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::ExchangeTokenResponse { + access_token: item.response.access_token, + }), + ..item.data + }) + } +} + +impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::ExchangeTokenRouterData) -> Result<Self, Self::Error> { + Ok(Self { + public_token: item.request.public_token.clone(), + }) + } +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidBankAccountCredentialsRequest { + access_token: String, + options: Option<BankAccountCredentialsOptions>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] + +pub struct PlaidBankAccountCredentialsResponse { + pub accounts: Vec<PlaidBankAccountCredentialsAccounts>, + pub numbers: PlaidBankAccountCredentialsNumbers, + // pub item: PlaidBankAccountCredentialsItem, + pub request_id: String, +} + +#[derive(Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub struct BankAccountCredentialsOptions { + account_ids: Vec<String>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] + +pub struct PlaidBankAccountCredentialsAccounts { + pub account_id: String, + pub name: String, + pub subtype: Option<String>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsBalances { + pub available: Option<i32>, + pub current: Option<i32>, + pub limit: Option<i32>, + pub iso_currency_code: Option<String>, + pub unofficial_currency_code: Option<String>, + pub last_updated_datetime: Option<String>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsNumbers { + pub ach: Vec<PlaidBankAccountCredentialsACH>, + pub eft: Vec<PlaidBankAccountCredentialsEFT>, + pub international: Vec<PlaidBankAccountCredentialsInternational>, + pub bacs: Vec<PlaidBankAccountCredentialsBacs>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsItem { + pub item_id: String, + pub institution_id: Option<String>, + pub webhook: Option<String>, + pub error: Option<PlaidErrorResponse>, +} +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsACH { + pub account_id: String, + pub account: String, + pub routing: String, + pub wire_routing: Option<String>, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsEFT { + pub account_id: String, + pub account: String, + pub institution: String, + pub branch: String, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsInternational { + pub account_id: String, + pub iban: String, + pub bic: String, +} + +#[derive(Debug, Deserialize, Eq, PartialEq)] +pub struct PlaidBankAccountCredentialsBacs { + pub account_id: String, + pub account: String, + pub sort_code: String, +} + +impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> { + Ok(Self { + access_token: item.request.access_token.clone(), + options: item.request.optional_ids.as_ref().map(|bank_account_ids| { + BankAccountCredentialsOptions { + account_ids: bank_account_ids.ids.clone(), + } + }), + }) + } +} + +impl<F, T> + TryFrom< + types::ResponseRouterData< + F, + PlaidBankAccountCredentialsResponse, + T, + types::BankAccountCredentialsResponse, + >, + > for types::PaymentAuthRouterData<F, T, types::BankAccountCredentialsResponse> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PlaidBankAccountCredentialsResponse, + T, + types::BankAccountCredentialsResponse, + >, + ) -> Result<Self, Self::Error> { + let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts); + let mut bank_account_vec = Vec::new(); + let mut id_to_suptype = HashMap::new(); + + accounts_info.into_iter().for_each(|acc| { + id_to_suptype.insert(acc.account_id, (acc.subtype, acc.name)); + }); + + account_numbers.ach.into_iter().for_each(|ach| { + let (acc_type, acc_name) = + if let Some((_type, name)) = id_to_suptype.get(&ach.account_id) { + (_type.to_owned(), Some(name.clone())) + } else { + (None, None) + }; + + let bank_details_new = types::BankAccountDetails { + account_name: acc_name, + account_number: ach.account, + routing_number: ach.routing, + payment_method_type: PaymentMethodType::Ach, + account_id: ach.account_id, + account_type: acc_type, + }; + + bank_account_vec.push(bank_details_new); + }); + + Ok(Self { + response: Ok(types::BankAccountCredentialsResponse { + credentials: bank_account_vec, + }), + ..item.data + }) + } +} +pub struct PlaidAuthType { + pub client_id: Secret<String>, + pub secret: Secret<String>, +} + +impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self { + client_id: client_id.to_owned(), + secret: secret.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} + +#[derive(Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub struct PlaidErrorResponse { + pub display_message: Option<String>, + pub error_code: Option<String>, + pub error_message: String, + pub error_type: Option<String>, +} diff --git a/crates/pm_auth/src/consts.rs b/crates/pm_auth/src/consts.rs new file mode 100644 index 00000000000..dac3485ec8f --- /dev/null +++ b/crates/pm_auth/src/consts.rs @@ -0,0 +1,5 @@ +pub const REQUEST_TIME_OUT: u64 = 30; // will timeout after the mentioned limit +pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; // timeout error code +pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; // error message for timed out request +pub const NO_ERROR_CODE: &str = "No error code"; +pub const NO_ERROR_MESSAGE: &str = "No error message"; diff --git a/crates/pm_auth/src/core.rs b/crates/pm_auth/src/core.rs new file mode 100644 index 00000000000..629e98fbf87 --- /dev/null +++ b/crates/pm_auth/src/core.rs @@ -0,0 +1 @@ +pub mod errors; diff --git a/crates/pm_auth/src/core/errors.rs b/crates/pm_auth/src/core/errors.rs new file mode 100644 index 00000000000..31b178a6276 --- /dev/null +++ b/crates/pm_auth/src/core/errors.rs @@ -0,0 +1,27 @@ +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum ConnectorError { + #[error("Failed to obtain authentication type")] + FailedToObtainAuthType, + #[error("Missing required field: {field_name}")] + MissingRequiredField { field_name: &'static str }, + #[error("Failed to execute a processing step: {0:?}")] + ProcessingStepFailed(Option<bytes::Bytes>), + #[error("Failed to deserialize connector response")] + ResponseDeserializationFailed, + #[error("Failed to encode connector request")] + RequestEncodingFailed, +} + +pub type CustomResult<T, E> = error_stack::Result<T, E>; + +#[derive(Debug, thiserror::Error)] +pub enum ParsingError { + #[error("Failed to parse enum: {0}")] + EnumParseFailure(&'static str), + #[error("Failed to parse struct: {0}")] + StructParseFailure(&'static str), + #[error("Failed to serialize to {0} format")] + EncodeError(&'static str), + #[error("Unknown error while parsing")] + UnknownError, +} diff --git a/crates/pm_auth/src/lib.rs b/crates/pm_auth/src/lib.rs new file mode 100644 index 00000000000..60d0e06a1e0 --- /dev/null +++ b/crates/pm_auth/src/lib.rs @@ -0,0 +1,4 @@ +pub mod connector; +pub mod consts; +pub mod core; +pub mod types; diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs new file mode 100644 index 00000000000..6f5875247f1 --- /dev/null +++ b/crates/pm_auth/src/types.rs @@ -0,0 +1,152 @@ +pub mod api; + +use std::marker::PhantomData; + +use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}; +use common_enums::PaymentMethodType; +use masking::Secret; +#[derive(Debug, Clone)] +pub struct PaymentAuthRouterData<F, Request, Response> { + pub flow: PhantomData<F>, + pub merchant_id: Option<String>, + pub connector: Option<String>, + pub request: Request, + pub response: Result<Response, ErrorResponse>, + pub connector_auth_type: ConnectorAuthType, + pub connector_http_status_code: Option<u16>, +} + +#[derive(Debug, Clone)] +pub struct LinkTokenRequest { + pub client_name: String, + pub country_codes: Option<Vec<String>>, + pub language: Option<String>, + pub user_info: Option<String>, +} + +#[derive(Debug, Clone)] +pub struct LinkTokenResponse { + pub link_token: String, +} + +pub type LinkTokenRouterData = + PaymentAuthRouterData<LinkToken, LinkTokenRequest, LinkTokenResponse>; + +#[derive(Debug, Clone)] +pub struct ExchangeTokenRequest { + pub public_token: String, +} + +#[derive(Debug, Clone)] +pub struct ExchangeTokenResponse { + pub access_token: String, +} + +impl From<ExchangeTokenResponse> for api_models::pm_auth::ExchangeTokenCreateResponse { + fn from(value: ExchangeTokenResponse) -> Self { + Self { + access_token: value.access_token, + } + } +} + +pub type ExchangeTokenRouterData = + PaymentAuthRouterData<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; + +#[derive(Debug, Clone)] +pub struct BankAccountCredentialsRequest { + pub access_token: String, + pub optional_ids: Option<BankAccountOptionalIDs>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountOptionalIDs { + pub ids: Vec<String>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountCredentialsResponse { + pub credentials: Vec<BankAccountDetails>, +} + +#[derive(Debug, Clone)] +pub struct BankAccountDetails { + pub account_name: Option<String>, + pub account_number: String, + pub routing_number: String, + pub payment_method_type: PaymentMethodType, + pub account_id: String, + pub account_type: Option<String>, +} + +pub type BankDetailsRouterData = PaymentAuthRouterData< + BankAccountCredentials, + BankAccountCredentialsRequest, + BankAccountCredentialsResponse, +>; + +pub type PaymentAuthLinkTokenType = + dyn self::api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>; + +pub type PaymentAuthExchangeTokenType = + dyn self::api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; + +pub type PaymentAuthBankAccountDetailsType = dyn self::api::ConnectorIntegration< + BankAccountCredentials, + BankAccountCredentialsRequest, + BankAccountCredentialsResponse, +>; + +#[derive(Clone, Debug, strum::EnumString, strum::Display)] +#[strum(serialize_all = "snake_case")] +pub enum PaymentMethodAuthConnectors { + Plaid, +} + +#[derive(Debug, Clone)] +pub struct ResponseRouterData<Flow, R, Request, Response> { + pub response: R, + pub data: PaymentAuthRouterData<Flow, Request, Response>, + pub http_code: u16, +} + +#[derive(Clone, Debug, serde::Serialize)] +pub struct ErrorResponse { + pub code: String, + pub message: String, + pub reason: Option<String>, + pub status_code: u16, +} + +impl ErrorResponse { + fn get_not_implemented() -> Self { + Self { + code: "IR_00".to_string(), + message: "This API is under development and will be made available soon.".to_string(), + reason: None, + status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), + } + } +} + +#[derive(Default, Debug, Clone, serde::Deserialize)] +pub enum ConnectorAuthType { + BodyKey { + client_id: Secret<String>, + secret: Secret<String>, + }, + #[default] + NoKey, +} + +#[derive(Clone, Debug)] +pub struct Response { + pub headers: Option<http::HeaderMap>, + pub response: bytes::Bytes, + pub status_code: u16, +} + +#[derive(serde::Deserialize, Clone)] +pub struct AuthServiceQueryParam { + pub client_secret: Option<String>, +} diff --git a/crates/pm_auth/src/types/api.rs b/crates/pm_auth/src/types/api.rs new file mode 100644 index 00000000000..2416d0fee1d --- /dev/null +++ b/crates/pm_auth/src/types/api.rs @@ -0,0 +1,167 @@ +pub mod auth_service; + +use std::fmt::Debug; + +use common_utils::{ + errors::CustomResult, + request::{Request, RequestBody}, +}; +use masking::Maskable; + +use crate::{ + core::errors::ConnectorError, + types::{self as auth_types, api::auth_service::AuthService}, +}; + +#[async_trait::async_trait] +pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync { + fn get_headers( + &self, + _req: &super::PaymentAuthRouterData<T, Req, Resp>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + Ok(vec![]) + } + + fn get_content_type(&self) -> &'static str { + mime::APPLICATION_JSON.essence_str() + } + + fn get_url( + &self, + _req: &super::PaymentAuthRouterData<T, Req, Resp>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> CustomResult<String, ConnectorError> { + Ok(String::new()) + } + + fn get_request_body( + &self, + _req: &super::PaymentAuthRouterData<T, Req, Resp>, + ) -> CustomResult<Option<RequestBody>, ConnectorError> { + Ok(None) + } + + fn build_request( + &self, + _req: &super::PaymentAuthRouterData<T, Req, Resp>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> CustomResult<Option<Request>, ConnectorError> { + Ok(None) + } + + fn handle_response( + &self, + data: &super::PaymentAuthRouterData<T, Req, Resp>, + _res: auth_types::Response, + ) -> CustomResult<super::PaymentAuthRouterData<T, Req, Resp>, ConnectorError> + where + T: Clone, + Req: Clone, + Resp: Clone, + { + Ok(data.clone()) + } + + fn get_error_response( + &self, + _res: auth_types::Response, + ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { + Ok(auth_types::ErrorResponse::get_not_implemented()) + } + + fn get_5xx_error_response( + &self, + res: auth_types::Response, + ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { + let error_message = match res.status_code { + 500 => "internal_server_error", + 501 => "not_implemented", + 502 => "bad_gateway", + 503 => "service_unavailable", + 504 => "gateway_timeout", + 505 => "http_version_not_supported", + 506 => "variant_also_negotiates", + 507 => "insufficient_storage", + 508 => "loop_detected", + 510 => "not_extended", + 511 => "network_authentication_required", + _ => "unknown_error", + }; + Ok(auth_types::ErrorResponse { + code: res.status_code.to_string(), + message: error_message.to_string(), + reason: String::from_utf8(res.response.to_vec()).ok(), + status_code: res.status_code, + }) + } +} + +pub trait ConnectorCommonExt<Flow, Req, Resp>: + ConnectorCommon + ConnectorIntegration<Flow, Req, Resp> +{ + fn build_headers( + &self, + _req: &auth_types::PaymentAuthRouterData<Flow, Req, Resp>, + _connectors: &auth_types::PaymentMethodAuthConnectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + Ok(Vec::new()) + } +} + +pub type BoxedConnectorIntegration<'a, T, Req, Resp> = + Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>; + +pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { + fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; +} + +impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S +where + S: ConnectorIntegration<T, Req, Resp>, +{ + fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> { + Box::new(self) + } +} + +pub trait AuthServiceConnector: AuthService + Send + Debug {} + +impl<T: Send + Debug + AuthService> AuthServiceConnector for T {} + +pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>; + +#[derive(Clone, Debug)] +pub struct PaymentAuthConnectorData { + pub connector: BoxedPaymentAuthConnector, + pub connector_name: super::PaymentMethodAuthConnectors, +} + +pub trait ConnectorCommon { + fn id(&self) -> &'static str; + + fn get_auth_header( + &self, + _auth_type: &auth_types::ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { + Ok(Vec::new()) + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str; + + fn build_error_response( + &self, + res: auth_types::Response, + ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { + Ok(auth_types::ErrorResponse { + status_code: res.status_code, + code: crate::consts::NO_ERROR_CODE.to_string(), + message: crate::consts::NO_ERROR_MESSAGE.to_string(), + reason: None, + }) + } +} diff --git a/crates/pm_auth/src/types/api/auth_service.rs b/crates/pm_auth/src/types/api/auth_service.rs new file mode 100644 index 00000000000..35d44970d51 --- /dev/null +++ b/crates/pm_auth/src/types/api/auth_service.rs @@ -0,0 +1,40 @@ +use crate::types::{ + BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest, + ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, +}; + +pub trait AuthService: + super::ConnectorCommon + + AuthServiceLinkToken + + AuthServiceExchangeToken + + AuthServiceBankAccountCredentials +{ +} + +#[derive(Debug, Clone)] +pub struct LinkToken; + +pub trait AuthServiceLinkToken: + super::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse> +{ +} + +#[derive(Debug, Clone)] +pub struct ExchangeToken; + +pub trait AuthServiceExchangeToken: + super::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse> +{ +} + +#[derive(Debug, Clone)] +pub struct BankAccountCredentials; + +pub trait AuthServiceBankAccountCredentials: + super::ConnectorIntegration< + BankAccountCredentials, + BankAccountCredentialsRequest, + BankAccountCredentialsResponse, +> +{ +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 791f617b30d..e498658e457 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -111,6 +111,7 @@ currency_conversion = { version = "0.1.0", path = "../currency_conversion" } data_models = { version = "0.1.0", path = "../data_models", default-features = false } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } +pm_auth = { version = "0.1.0", path = "../pm_auth", package = "pm_auth" } external_services = { version = "0.1.0", path = "../external_services" } kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" } masking = { version = "0.1.0", path = "../masking" } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 6cbffc186d2..0d098b9acab 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -100,6 +100,7 @@ pub struct Settings { pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, pub webhook_source_verification_call: WebhookSourceVerificationCall, + pub payment_method_auth: PaymentMethodAuth, pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig, #[cfg(feature = "payouts")] pub payouts: Payouts, @@ -154,6 +155,12 @@ pub struct ForexApi { pub redis_lock_timeout: u64, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct PaymentMethodAuth { + pub redis_expiry: i64, + pub pm_auth_key: String, +} + #[derive(Debug, Deserialize, Clone, Default)] pub struct DefaultExchangeRates { pub base_currency: String, diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs index be83de84916..0bd197ee22e 100644 --- a/crates/router/src/core.rs +++ b/crates/router/src/core.rs @@ -24,6 +24,7 @@ pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; +pub mod pm_auth; pub mod refunds; pub mod routing; pub mod surcharge_decision_config; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 5ab543d382f..113bc7d677d 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -10,9 +10,10 @@ use common_utils::{ ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt}, pii, }; -use error_stack::{report, FutureExt, ResultExt}; +use error_stack::{report, FutureExt, IntoReport, ResultExt}; use futures::future::try_join_all; use masking::{PeekInterface, Secret}; +use pm_auth::connector::plaid::transformers::PlaidAuthType; use uuid::Uuid; use crate::{ @@ -762,7 +763,7 @@ pub async fn create_payment_connector( ) .await?; - let routable_connector = + let mut routable_connector = api_enums::RoutableConnectors::from_str(&req.connector_name.to_string()).ok(); let business_profile = state @@ -773,6 +774,30 @@ pub async fn create_payment_connector( id: profile_id.to_owned(), })?; + let pm_auth_connector = + api_enums::convert_pm_auth_connector(req.connector_name.to_string().as_str()); + + let is_unroutable_connector = if pm_auth_connector.is_some() { + if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid connector type given".to_string(), + }) + .into_report(); + } + true + } else { + let routable_connector_option = req + .connector_name + .to_string() + .parse() + .into_report() + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid connector name given".to_string(), + })?; + routable_connector = Some(routable_connector_option); + false + }; + // If connector label is not passed in the request, generate one let connector_label = req .connector_label @@ -877,6 +902,20 @@ pub async fn create_payment_connector( api_enums::ConnectorStatus::Active, )?; + if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth { + if let Some(val) = req.pm_auth_config.clone() { + validate_pm_auth( + val, + &*state.clone().store, + merchant_id.clone().as_str(), + &key_store, + merchant_account, + &Some(profile_id.clone()), + ) + .await?; + } + } + let merchant_connector_account = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_string(), connector_type: req.connector_type, @@ -948,7 +987,7 @@ pub async fn create_payment_connector( #[cfg(feature = "connector_choice_mca_id")] merchant_connector_id: Some(mca.merchant_connector_id.clone()), #[cfg(not(feature = "connector_choice_mca_id"))] - sub_label: req.business_sub_label, + sub_label: req.business_sub_label.clone(), }; if !default_routing_config.contains(&choice) { @@ -956,7 +995,7 @@ pub async fn create_payment_connector( routing_helpers::update_merchant_default_config( &*state.store, merchant_id, - default_routing_config, + default_routing_config.clone(), ) .await?; } @@ -965,7 +1004,7 @@ pub async fn create_payment_connector( routing_helpers::update_merchant_default_config( &*state.store, &profile_id.clone(), - default_routing_config_for_profile, + default_routing_config_for_profile.clone(), ) .await?; } @@ -980,10 +1019,92 @@ pub async fn create_payment_connector( ], ); + if !is_unroutable_connector { + if let Some(routable_connector_val) = routable_connector { + let choice = routing_types::RoutableConnectorChoice { + #[cfg(feature = "backwards_compatibility")] + choice_kind: routing_types::RoutableChoiceKind::FullStruct, + connector: routable_connector_val, + #[cfg(feature = "connector_choice_mca_id")] + merchant_connector_id: Some(mca.merchant_connector_id.clone()), + #[cfg(not(feature = "connector_choice_mca_id"))] + sub_label: req.business_sub_label.clone(), + }; + + if !default_routing_config.contains(&choice) { + default_routing_config.push(choice.clone()); + routing_helpers::update_merchant_default_config( + &*state.clone().store, + merchant_id, + default_routing_config, + ) + .await?; + } + + if !default_routing_config_for_profile.contains(&choice) { + default_routing_config_for_profile.push(choice); + routing_helpers::update_merchant_default_config( + &*state.store, + &profile_id, + default_routing_config_for_profile, + ) + .await?; + } + } + }; + let mca_response = mca.try_into()?; Ok(service_api::ApplicationResponse::Json(mca_response)) } +async fn validate_pm_auth( + val: serde_json::Value, + db: &dyn StorageInterface, + merchant_id: &str, + key_store: &domain::MerchantKeyStore, + merchant_account: domain::MerchantAccount, + profile_id: &Option<String>, +) -> RouterResponse<()> { + let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(val) + .into_report() + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: "invalid data received for payment method auth config".to_string(), + }) + .attach_printable("Failed to deserialize Payment Method Auth config")?; + + let all_mcas = db + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + merchant_id, + true, + key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_account.merchant_id.clone(), + })?; + + for conn_choice in config.enabled_payment_methods { + let pm_auth_mca = all_mcas + .clone() + .into_iter() + .find(|mca| mca.merchant_connector_id == conn_choice.mca_id) + .ok_or(errors::ApiErrorResponse::GenericNotFoundError { + message: "payment method auth connector account not found".to_string(), + }) + .into_report()?; + + if &pm_auth_mca.profile_id != profile_id { + return Err(errors::ApiErrorResponse::GenericNotFoundError { + message: "payment method auth profile_id differs from connector profile_id" + .to_string(), + }) + .into_report(); + } + } + + Ok(services::ApplicationResponse::StatusOk) +} + pub async fn retrieve_payment_connector( state: AppState, merchant_id: String, @@ -1066,7 +1187,7 @@ pub async fn update_payment_connector( .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let _merchant_account = db + let merchant_account = db .find_merchant_account_by_merchant_id(merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; @@ -1106,6 +1227,20 @@ pub async fn update_payment_connector( let (connector_status, disabled) = validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?; + if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth { + if let Some(val) = req.pm_auth_config.clone() { + validate_pm_auth( + val, + db, + merchant_id, + &key_store, + merchant_account, + &mca.profile_id, + ) + .await?; + } + } + let payment_connector = storage::MerchantConnectorAccountUpdate::Update { merchant_id: None, connector_type: Some(req.connector_type), @@ -1720,8 +1855,10 @@ pub(crate) fn validate_auth_and_metadata_type( signifyd::transformers::SignifydAuthType::try_from(val)?; Ok(()) } - api_enums::Connector::Plaid => Err(report!(errors::ConnectorError::InvalidConnectorName) - .attach_printable(format!("invalid connector name: {connector_name}"))), + api_enums::Connector::Plaid => { + PlaidAuthType::foreign_try_from(val)?; + Ok(()) + } } } diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index a2dbfb1480c..14a39f1d955 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -11,12 +11,12 @@ pub use api_models::{ pub use common_utils::request::RequestBody; use data_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; use diesel_models::enums; -use error_stack::IntoReport; use crate::{ core::{ - errors::{self, RouterResult}, + errors::RouterResult, payments::helpers, + pm_auth::{self as core_pm_auth}, }, routes::AppState, types::{ @@ -172,11 +172,14 @@ impl PaymentMethodRetrieve for Oss { .map(|card| Some((card, enums::PaymentMethod::Card))) } - storage::PaymentTokenData::AuthBankDebit(_) => { - Err(errors::ApiErrorResponse::NotImplemented { - message: errors::NotImplementedMessage::Default, - }) - .into_report() + storage::PaymentTokenData::AuthBankDebit(auth_token) => { + core_pm_auth::retrieve_payment_method_from_auth_service( + state, + merchant_key_store, + auth_token, + payment_intent, + ) + .await } } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index bbcfe45a1d0..84aef952a53 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -13,6 +13,7 @@ use api_models::{ ResponsePaymentMethodsEnabled, }, payments::BankCodeResponse, + pm_auth::PaymentMethodAuthConfig, surcharge_decision_configs as api_surcharge_decision_configs, }; use common_utils::{ @@ -29,6 +30,8 @@ use super::surcharge_decision_configs::{ perform_surcharge_decision_management_for_payment_method_list, perform_surcharge_decision_management_for_saved_cards, }; +#[cfg(not(feature = "connector_choice_mca_id"))] +use crate::core::utils::get_connector_label; use crate::{ configs::settings, core::{ @@ -1081,9 +1084,9 @@ pub async fn list_payment_methods( logger::debug!(mca_before_filtering=?filtered_mcas); let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![]; - for mca in filtered_mcas { - let payment_methods = match mca.payment_methods_enabled { - Some(pm) => pm, + for mca in &filtered_mcas { + let payment_methods = match &mca.payment_methods_enabled { + Some(pm) => pm.clone(), None => continue, }; @@ -1094,13 +1097,15 @@ pub async fn list_payment_methods( payment_intent.as_ref(), payment_attempt.as_ref(), billing_address.as_ref(), - mca.connector_name, + mca.connector_name.clone(), pm_config_mapping, &state.conf.mandates.supported_payment_methods, ) .await?; } + let mut pmt_to_auth_connector = HashMap::new(); + if let Some((payment_attempt, payment_intent)) = payment_attempt.as_ref().zip(payment_intent.as_ref()) { @@ -1204,6 +1209,84 @@ pub async fn list_payment_methods( pre_routing_results.insert(pm_type, routable_choice); } + let redis_conn = db + .get_redis_conn() + .map_err(|redis_error| logger::error!(?redis_error)) + .ok(); + + let mut val = Vec::new(); + + for (payment_method_type, routable_connector_choice) in &pre_routing_results { + #[cfg(not(feature = "connector_choice_mca_id"))] + let connector_label = get_connector_label( + payment_intent.business_country, + payment_intent.business_label.as_ref(), + #[cfg(not(feature = "connector_choice_mca_id"))] + routable_connector_choice.sub_label.as_ref(), + #[cfg(feature = "connector_choice_mca_id")] + None, + routable_connector_choice.connector.to_string().as_str(), + ); + #[cfg(not(feature = "connector_choice_mca_id"))] + let matched_mca = filtered_mcas + .iter() + .find(|m| connector_label == m.connector_label); + + #[cfg(feature = "connector_choice_mca_id")] + let matched_mca = filtered_mcas.iter().find(|m| { + routable_connector_choice.merchant_connector_id.as_ref() + == Some(&m.merchant_connector_id) + }); + + if let Some(m) = matched_mca { + let pm_auth_config = m + .pm_auth_config + .as_ref() + .map(|config| { + serde_json::from_value::<PaymentMethodAuthConfig>(config.clone()) + .into_report() + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to deserialize Payment Method Auth config") + }) + .transpose() + .unwrap_or_else(|err| { + logger::error!(error=?err); + None + }); + + let matched_config = match pm_auth_config { + Some(config) => { + let internal_config = config + .enabled_payment_methods + .iter() + .find(|config| config.payment_method_type == *payment_method_type) + .cloned(); + + internal_config + } + None => None, + }; + + if let Some(config) = matched_config { + pmt_to_auth_connector + .insert(*payment_method_type, config.connector_name.clone()); + val.push(config); + } + } + } + + let pm_auth_key = format!("pm_auth_{}", payment_intent.payment_id); + let redis_expiry = state.conf.payment_method_auth.redis_expiry; + + if let Some(rc) = redis_conn { + rc.serialize_and_set_key_with_expiry(pm_auth_key.as_str(), val, redis_expiry) + .await + .attach_printable("Failed to store pm auth data in redis") + .unwrap_or_else(|err| { + logger::error!(error=?err); + }) + }; + routing_info.pre_routing_results = Some(pre_routing_results); let encoded = utils::Encode::<storage::PaymentRoutingInfo>::encode_to_value(&routing_info) @@ -1461,7 +1544,9 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector + .get(payment_method_types_hm.0) + .cloned(), }) } @@ -1496,7 +1581,9 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(payment_method_types_hm.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector + .get(payment_method_types_hm.0) + .cloned(), }) } @@ -1526,7 +1613,7 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(), } }) } @@ -1559,7 +1646,7 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(), } }) } @@ -1592,7 +1679,7 @@ pub async fn list_payment_methods( .and_then(|inner_hm| inner_hm.get(key.0)) .cloned(), surcharge_details: None, - pm_auth_connector: None, + pm_auth_connector: pmt_to_auth_connector.get(&payment_method_type).cloned(), } }) } diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs new file mode 100644 index 00000000000..821f049d8cf --- /dev/null +++ b/crates/router/src/core/pm_auth.rs @@ -0,0 +1,729 @@ +use std::{collections::HashMap, str::FromStr}; + +use api_models::{ + enums, + payment_methods::{self, BankAccountAccessCreds}, + payments::{AddressDetails, BankDebitBilling, BankDebitData, PaymentMethodData}, +}; +use hex; +pub mod helpers; +pub mod transformers; + +use common_utils::{ + consts, + crypto::{HmacSha256, SignMessage}, + ext_traits::AsyncExt, + generate_id, +}; +use data_models::payments::PaymentIntent; +use error_stack::{IntoReport, ResultExt}; +#[cfg(feature = "kms")] +pub use external_services::kms; +use helpers::PaymentAuthConnectorDataExt; +use masking::{ExposeInterface, PeekInterface}; +use pm_auth::{ + connector::plaid::transformers::PlaidAuthType, + types::{ + self as pm_auth_types, + api::{ + auth_service::{BankAccountCredentials, ExchangeToken, LinkToken}, + BoxedConnectorIntegration, PaymentAuthConnectorData, + }, + }, +}; + +use crate::{ + core::{ + errors::{self, ApiErrorResponse, RouterResponse, RouterResult, StorageErrorExt}, + payment_methods::cards, + payments::helpers as oss_helpers, + pm_auth::helpers::{self as pm_auth_helpers}, + }, + db::StorageInterface, + logger, + routes::AppState, + services::{ + pm_auth::{self as pm_auth_services}, + ApplicationResponse, + }, + types::{ + self, + domain::{self, types::decrypt}, + storage, + transformers::ForeignTryFrom, + }, +}; + +pub async fn create_link_token( + state: AppState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + payload: api_models::pm_auth::LinkTokenCreateRequest, +) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> { + let db = &*state.store; + + let redis_conn = db + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let pm_auth_key = format!("pm_auth_{}", payload.payment_id); + + let pm_auth_configs = redis_conn + .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( + pm_auth_key.as_str(), + "Vec<PaymentMethodAuthConnectorChoice>", + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get payment method auth choices from redis")?; + + let selected_config = pm_auth_configs + .into_iter() + .find(|config| { + config.payment_method == payload.payment_method + && config.payment_method_type == payload.payment_method_type + }) + .ok_or(ApiErrorResponse::GenericNotFoundError { + message: "payment method auth connector name not found".to_string(), + }) + .into_report()?; + + let connector_name = selected_config.connector_name.as_str(); + + let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?; + let connector_integration: BoxedConnectorIntegration< + '_, + LinkToken, + pm_auth_types::LinkTokenRequest, + pm_auth_types::LinkTokenResponse, + > = connector.connector.get_connector_integration(); + + let payment_intent = oss_helpers::verify_payment_intent_time_and_client_secret( + &*state.store, + &merchant_account, + payload.client_secret, + ) + .await?; + + let billing_country = payment_intent + .as_ref() + .async_map(|pi| async { + oss_helpers::get_address_by_id( + &*state.store, + pi.billing_address_id.clone(), + &key_store, + pi.payment_id.clone(), + merchant_account.merchant_id.clone(), + merchant_account.storage_scheme, + ) + .await + }) + .await + .transpose()? + .flatten() + .and_then(|address| address.country) + .map(|country| country.to_string()); + + let merchant_connector_account = state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + merchant_account.merchant_id.as_str(), + &selected_config.mca_id, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_account.merchant_id.clone(), + })?; + + let auth_type = helpers::get_connector_auth_type(merchant_connector_account)?; + + let router_data = pm_auth_types::LinkTokenRouterData { + flow: std::marker::PhantomData, + merchant_id: Some(merchant_account.merchant_id), + connector: Some(connector_name.to_string()), + request: pm_auth_types::LinkTokenRequest { + client_name: "HyperSwitch".to_string(), + country_codes: Some(vec![billing_country.ok_or( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "billing_country", + }, + )?]), + language: payload.language, + user_info: payment_intent.and_then(|pi| pi.customer_id), + }, + response: Ok(pm_auth_types::LinkTokenResponse { + link_token: "".to_string(), + }), + connector_http_status_code: None, + connector_auth_type: auth_type, + }; + + let connector_resp = pm_auth_services::execute_connector_processing_step( + state.as_ref(), + connector_integration, + &router_data, + &connector.connector_name, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed while calling link token creation connector api")?; + + let link_token_resp = + connector_resp + .response + .map_err(|err| ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: connector.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + })?; + + let response = api_models::pm_auth::LinkTokenCreateResponse { + link_token: link_token_resp.link_token, + connector: connector.connector_name.to_string(), + }; + + Ok(ApplicationResponse::Json(response)) +} + +impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType { + type Error = errors::ConnectorError; + + fn foreign_try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::BodyKey { api_key, key1 } => { + Ok::<Self, errors::ConnectorError>(Self { + client_id: api_key.to_owned(), + secret: key1.to_owned(), + }) + } + _ => Err(errors::ConnectorError::FailedToObtainAuthType), + } + } +} + +pub async fn exchange_token_core( + state: AppState, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + payload: api_models::pm_auth::ExchangeTokenCreateRequest, +) -> RouterResponse<()> { + let db = &*state.store; + + let config = get_selected_config_from_redis(db, &payload).await?; + + let connector_name = config.connector_name.as_str(); + + let connector = + pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(connector_name)?; + + let merchant_connector_account = state + .store + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + merchant_account.merchant_id.as_str(), + &config.mca_id, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_account.merchant_id.clone(), + })?; + + let auth_type = helpers::get_connector_auth_type(merchant_connector_account.clone())?; + + let access_token = get_access_token_from_exchange_api( + &connector, + connector_name, + &payload, + &auth_type, + &state, + ) + .await?; + + let bank_account_details_resp = get_bank_account_creds( + connector, + &merchant_account, + connector_name, + &access_token, + auth_type, + &state, + None, + ) + .await?; + + Box::pin(store_bank_details_in_payment_methods( + key_store, + payload, + merchant_account, + state, + bank_account_details_resp, + (connector_name, access_token), + merchant_connector_account.merchant_connector_id, + )) + .await?; + + Ok(ApplicationResponse::StatusOk) +} + +async fn store_bank_details_in_payment_methods( + key_store: domain::MerchantKeyStore, + payload: api_models::pm_auth::ExchangeTokenCreateRequest, + merchant_account: domain::MerchantAccount, + state: AppState, + bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse, + connector_details: (&str, String), + mca_id: String, +) -> RouterResult<()> { + let key = key_store.key.get_inner().peek(); + let db = &*state.clone().store; + let (connector_name, access_token) = connector_details; + + let payment_intent = db + .find_payment_intent_by_payment_id_merchant_id( + &payload.payment_id, + &merchant_account.merchant_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(ApiErrorResponse::PaymentNotFound)?; + + let customer_id = payment_intent + .customer_id + .ok_or(ApiErrorResponse::CustomerNotFound)?; + + let payment_methods = db + .find_payment_method_by_customer_id_merchant_id_list( + &customer_id, + &merchant_account.merchant_id, + ) + .await + .change_context(ApiErrorResponse::InternalServerError)?; + + let mut hash_to_payment_method: HashMap< + String, + ( + storage::PaymentMethod, + payment_methods::PaymentMethodDataBankCreds, + ), + > = HashMap::new(); + + for pm in payment_methods { + if pm.payment_method == enums::PaymentMethod::BankDebit { + let bank_details_pm_data = decrypt::<serde_json::Value, masking::WithType>( + pm.payment_method_data.clone(), + key, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("unable to decrypt bank account details")? + .map(|x| x.into_inner().expose()) + .map(|v| { + serde_json::from_value::<payment_methods::PaymentMethodsData>(v) + .into_report() + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("Failed to deserialize Payment Method Auth config") + }) + .transpose() + .unwrap_or_else(|err| { + logger::error!(error=?err); + None + }) + .and_then(|pmd| match pmd { + payment_methods::PaymentMethodsData::BankDetails(bank_creds) => Some(bank_creds), + _ => None, + }) + .ok_or(ApiErrorResponse::InternalServerError)?; + + hash_to_payment_method.insert( + bank_details_pm_data.hash.clone(), + (pm, bank_details_pm_data), + ); + } + } + + #[cfg(feature = "kms")] + let pm_auth_key = kms::get_kms_client(&state.conf.kms) + .await + .decrypt(state.conf.payment_method_auth.pm_auth_key.clone()) + .await + .change_context(ApiErrorResponse::InternalServerError)?; + + #[cfg(not(feature = "kms"))] + let pm_auth_key = state.conf.payment_method_auth.pm_auth_key.clone(); + + let mut update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)> = + Vec::new(); + let mut new_entries: Vec<storage::PaymentMethodNew> = Vec::new(); + + for creds in bank_account_details_resp.credentials { + let hash_string = format!("{}-{}", creds.account_number, creds.routing_number); + let generated_hash = hex::encode( + HmacSha256::sign_message(&HmacSha256, pm_auth_key.as_bytes(), hash_string.as_bytes()) + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed to sign the message")?, + ); + + let contains_account = hash_to_payment_method.get(&generated_hash); + let mut pmd = payment_methods::PaymentMethodDataBankCreds { + mask: creds + .account_number + .chars() + .rev() + .take(4) + .collect::<String>() + .chars() + .rev() + .collect::<String>(), + hash: generated_hash, + account_type: creds.account_type, + account_name: creds.account_name, + payment_method_type: creds.payment_method_type, + connector_details: vec![payment_methods::BankAccountConnectorDetails { + connector: connector_name.to_string(), + mca_id: mca_id.clone(), + access_token: payment_methods::BankAccountAccessCreds::AccessToken( + access_token.clone(), + ), + account_id: creds.account_id, + }], + }; + + if let Some((pm, details)) = contains_account { + pmd.connector_details.extend( + details + .connector_details + .clone() + .into_iter() + .filter(|conn| conn.mca_id != mca_id), + ); + + let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); + let encrypted_data = + cards::create_encrypted_payment_method_data(&key_store, Some(payment_method_data)) + .await + .ok_or(ApiErrorResponse::InternalServerError)?; + let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate { + payment_method_data: Some(encrypted_data), + }; + + update_entries.push((pm.clone(), pm_update)); + } else { + let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd); + let encrypted_data = + cards::create_encrypted_payment_method_data(&key_store, Some(payment_method_data)) + .await + .ok_or(ApiErrorResponse::InternalServerError)?; + let pm_id = generate_id(consts::ID_LENGTH, "pm"); + let pm_new = storage::PaymentMethodNew { + customer_id: customer_id.clone(), + merchant_id: merchant_account.merchant_id.clone(), + payment_method_id: pm_id, + payment_method: enums::PaymentMethod::BankDebit, + payment_method_type: Some(creds.payment_method_type), + payment_method_issuer: None, + scheme: None, + metadata: None, + payment_method_data: Some(encrypted_data), + ..storage::PaymentMethodNew::default() + }; + + new_entries.push(pm_new); + }; + } + + store_in_db(update_entries, new_entries, db).await?; + + Ok(()) +} + +async fn store_in_db( + update_entries: Vec<(storage::PaymentMethod, storage::PaymentMethodUpdate)>, + new_entries: Vec<storage::PaymentMethodNew>, + db: &dyn StorageInterface, +) -> RouterResult<()> { + let update_entries_futures = update_entries + .into_iter() + .map(|(pm, pm_update)| db.update_payment_method(pm, pm_update)) + .collect::<Vec<_>>(); + + let new_entries_futures = new_entries + .into_iter() + .map(|pm_new| db.insert_payment_method(pm_new)) + .collect::<Vec<_>>(); + + let update_futures = futures::future::join_all(update_entries_futures); + let new_futures = futures::future::join_all(new_entries_futures); + + let (update, new) = tokio::join!(update_futures, new_futures); + + let _ = update + .into_iter() + .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}"))); + + let _ = new + .into_iter() + .map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}"))); + + Ok(()) +} + +pub async fn get_bank_account_creds( + connector: PaymentAuthConnectorData, + merchant_account: &domain::MerchantAccount, + connector_name: &str, + access_token: &str, + auth_type: pm_auth_types::ConnectorAuthType, + state: &AppState, + bank_account_id: Option<String>, +) -> RouterResult<pm_auth_types::BankAccountCredentialsResponse> { + let connector_integration_bank_details: BoxedConnectorIntegration< + '_, + BankAccountCredentials, + pm_auth_types::BankAccountCredentialsRequest, + pm_auth_types::BankAccountCredentialsResponse, + > = connector.connector.get_connector_integration(); + + let router_data_bank_details = pm_auth_types::BankDetailsRouterData { + flow: std::marker::PhantomData, + merchant_id: Some(merchant_account.merchant_id.clone()), + connector: Some(connector_name.to_string()), + request: pm_auth_types::BankAccountCredentialsRequest { + access_token: access_token.to_string(), + optional_ids: bank_account_id + .map(|id| pm_auth_types::BankAccountOptionalIDs { ids: vec![id] }), + }, + response: Ok(pm_auth_types::BankAccountCredentialsResponse { + credentials: Vec::new(), + }), + connector_http_status_code: None, + connector_auth_type: auth_type, + }; + + let bank_details_resp = pm_auth_services::execute_connector_processing_step( + state, + connector_integration_bank_details, + &router_data_bank_details, + &connector.connector_name, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed while calling bank account details connector api")?; + + let bank_account_details_resp = + bank_details_resp + .response + .map_err(|err| ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: connector.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + })?; + + Ok(bank_account_details_resp) +} + +async fn get_access_token_from_exchange_api( + connector: &PaymentAuthConnectorData, + connector_name: &str, + payload: &api_models::pm_auth::ExchangeTokenCreateRequest, + auth_type: &pm_auth_types::ConnectorAuthType, + state: &AppState, +) -> RouterResult<String> { + let connector_integration: BoxedConnectorIntegration< + '_, + ExchangeToken, + pm_auth_types::ExchangeTokenRequest, + pm_auth_types::ExchangeTokenResponse, + > = connector.connector.get_connector_integration(); + + let router_data = pm_auth_types::ExchangeTokenRouterData { + flow: std::marker::PhantomData, + merchant_id: None, + connector: Some(connector_name.to_string()), + request: pm_auth_types::ExchangeTokenRequest { + public_token: payload.public_token.clone(), + }, + response: Ok(pm_auth_types::ExchangeTokenResponse { + access_token: "".to_string(), + }), + connector_http_status_code: None, + connector_auth_type: auth_type.clone(), + }; + + let resp = pm_auth_services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + &connector.connector_name, + ) + .await + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed while calling exchange token connector api")?; + + let exchange_token_resp = + resp.response + .map_err(|err| ApiErrorResponse::ExternalConnectorError { + code: err.code, + message: err.message, + connector: connector.connector_name.to_string(), + status_code: err.status_code, + reason: err.reason, + })?; + + let access_token = exchange_token_resp.access_token; + Ok(access_token) +} + +async fn get_selected_config_from_redis( + db: &dyn StorageInterface, + payload: &api_models::pm_auth::ExchangeTokenCreateRequest, +) -> RouterResult<api_models::pm_auth::PaymentMethodAuthConnectorChoice> { + let redis_conn = db + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let pm_auth_key = format!("pm_auth_{}", payload.payment_id); + + let pm_auth_configs = redis_conn + .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( + pm_auth_key.as_str(), + "Vec<PaymentMethodAuthConnectorChoice>", + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get payment method auth choices from redis")?; + + let selected_config = pm_auth_configs + .iter() + .find(|conf| { + conf.payment_method == payload.payment_method + && conf.payment_method_type == payload.payment_method_type + }) + .ok_or(ApiErrorResponse::GenericNotFoundError { + message: "connector name not found".to_string(), + }) + .into_report()? + .clone(); + + Ok(selected_config) +} + +pub async fn retrieve_payment_method_from_auth_service( + state: &AppState, + key_store: &domain::MerchantKeyStore, + auth_token: &payment_methods::BankAccountConnectorDetails, + payment_intent: &PaymentIntent, +) -> RouterResult<Option<(PaymentMethodData, enums::PaymentMethod)>> { + let db = state.store.as_ref(); + + let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name( + auth_token.connector.as_str(), + )?; + + let merchant_account = db + .find_merchant_account_by_merchant_id(&payment_intent.merchant_id, key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let mca = db + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + &payment_intent.merchant_id, + &auth_token.mca_id, + key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: auth_token.mca_id.clone(), + }) + .attach_printable( + "error while fetching merchant_connector_account from merchant_id and connector name", + )?; + + let auth_type = pm_auth_helpers::get_connector_auth_type(mca)?; + + let BankAccountAccessCreds::AccessToken(access_token) = &auth_token.access_token; + + let bank_account_creds = get_bank_account_creds( + connector, + &merchant_account, + &auth_token.connector, + access_token, + auth_type, + state, + Some(auth_token.account_id.clone()), + ) + .await?; + + logger::debug!("bank_creds: {:?}", bank_account_creds); + + let bank_account = bank_account_creds + .credentials + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .into_report() + .attach_printable("Bank account details not found")?; + + let mut bank_type = None; + if let Some(account_type) = bank_account.account_type.clone() { + bank_type = api_models::enums::BankType::from_str(account_type.as_str()) + .map_err(|error| logger::error!(%error,"unable to parse account_type {account_type:?}")) + .ok(); + } + + let address = oss_helpers::get_address_by_id( + &*state.store, + payment_intent.billing_address_id.clone(), + key_store, + payment_intent.payment_id.clone(), + merchant_account.merchant_id.clone(), + merchant_account.storage_scheme, + ) + .await?; + + let name = address + .as_ref() + .and_then(|addr| addr.first_name.clone().map(|name| name.into_inner())); + + let address_details = address.clone().map(|addr| { + let line1 = addr.line1.map(|line1| line1.into_inner()); + let line2 = addr.line2.map(|line2| line2.into_inner()); + let line3 = addr.line3.map(|line3| line3.into_inner()); + let zip = addr.zip.map(|zip| zip.into_inner()); + let state = addr.state.map(|state| state.into_inner()); + let first_name = addr.first_name.map(|first_name| first_name.into_inner()); + let last_name = addr.last_name.map(|last_name| last_name.into_inner()); + + AddressDetails { + city: addr.city, + country: addr.country, + line1, + line2, + line3, + zip, + state, + first_name, + last_name, + } + }); + let payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { + billing_details: BankDebitBilling { + name: name.unwrap_or_default(), + email: common_utils::pii::Email::from(masking::Secret::new("".to_string())), + address: address_details, + }, + account_number: masking::Secret::new(bank_account.account_number.clone()), + routing_number: masking::Secret::new(bank_account.routing_number.clone()), + card_holder_name: None, + bank_account_holder_name: None, + bank_name: None, + bank_type, + bank_holder_type: None, + }); + + Ok(Some((payment_method_data, enums::PaymentMethod::BankDebit))) +} diff --git a/crates/router/src/core/pm_auth/helpers.rs b/crates/router/src/core/pm_auth/helpers.rs new file mode 100644 index 00000000000..43d30705a80 --- /dev/null +++ b/crates/router/src/core/pm_auth/helpers.rs @@ -0,0 +1,33 @@ +use common_utils::ext_traits::ValueExt; +use error_stack::{IntoReport, ResultExt}; +use pm_auth::types::{self as pm_auth_types, api::BoxedPaymentAuthConnector}; + +use crate::{ + core::errors::{self, ApiErrorResponse}, + types::{self, domain, transformers::ForeignTryFrom}, +}; + +pub trait PaymentAuthConnectorDataExt { + fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse> + where + Self: Sized; + fn convert_connector( + connector_name: pm_auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse>; +} + +pub fn get_connector_auth_type( + merchant_connector_account: domain::MerchantConnectorAccount, +) -> errors::CustomResult<pm_auth_types::ConnectorAuthType, ApiErrorResponse> { + let auth_type: types::ConnectorAuthType = merchant_connector_account + .connector_account_details + .parse_value("ConnectorAuthType") + .change_context(ApiErrorResponse::MerchantConnectorAccountNotFound { + id: "ConnectorAuthType".to_string(), + })?; + + pm_auth_types::ConnectorAuthType::foreign_try_from(auth_type) + .into_report() + .change_context(ApiErrorResponse::InternalServerError) + .attach_printable("Failed while converting ConnectorAuthType") +} diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs new file mode 100644 index 00000000000..8a1369c2e02 --- /dev/null +++ b/crates/router/src/core/pm_auth/transformers.rs @@ -0,0 +1,18 @@ +use pm_auth::types::{self as pm_auth_types}; + +use crate::{core::errors, types, types::transformers::ForeignTryFrom}; + +impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthType { + type Error = errors::ConnectorError; + fn foreign_try_from(auth_type: types::ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + types::ConnectorAuthType::BodyKey { api_key, key1 } => { + Ok::<Self, errors::ConnectorError>(Self::BodyKey { + client_id: api_key.to_owned(), + secret: key1.to_owned(), + }) + } + _ => Err(errors::ConnectorError::FailedToObtainAuthType), + } + } +} diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index ce1717c9e93..ec718b2dde9 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -40,6 +40,8 @@ pub mod verify_connector; pub mod webhooks; pub mod locker_migration; +#[cfg(any(feature = "olap", feature = "oltp"))] +pub mod pm_auth; #[cfg(feature = "dummy_connector")] pub use self::app::DummyConnector; #[cfg(any(feature = "olap", feature = "oltp"))] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 6b72e69b9f4..a7c394b7b6c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -20,6 +20,8 @@ use super::currency; use super::dummy_connector::*; #[cfg(feature = "payouts")] use super::payouts::*; +#[cfg(feature = "oltp")] +use super::pm_auth; #[cfg(feature = "olap")] use super::routing as cloud_routing; #[cfg(all(feature = "olap", feature = "kms"))] @@ -555,6 +557,8 @@ impl PaymentMethods { .route(web::post().to(payment_method_update_api)) .route(web::delete().to(payment_method_delete_api)), ) + .service(web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create))) + .service(web::resource("/auth/exchange").route(web::post().to(pm_auth::exchange_token))) } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 88c35bb0a13..533d1d3a629 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -13,6 +13,7 @@ pub enum ApiIdentifier { Ephemeral, Mandates, PaymentMethods, + PaymentMethodAuth, Payouts, Disputes, CardsInfo, @@ -86,6 +87,8 @@ impl From<Flow> for ApiIdentifier { | Flow::PaymentMethodsDelete | Flow::ValidatePaymentMethod => Self::PaymentMethods, + Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth, + Flow::PaymentsCreate | Flow::PaymentsRetrieve | Flow::PaymentsUpdate diff --git a/crates/router/src/routes/pm_auth.rs b/crates/router/src/routes/pm_auth.rs new file mode 100644 index 00000000000..cfadd787c31 --- /dev/null +++ b/crates/router/src/routes/pm_auth.rs @@ -0,0 +1,73 @@ +use actix_web::{web, HttpRequest, Responder}; +use api_models as api_types; +use router_env::{instrument, tracing, types::Flow}; + +use crate::{core::api_locking, routes::AppState, services::api as oss_api}; + +#[instrument(skip_all, fields(flow = ?Flow::PmAuthLinkTokenCreate))] +pub async fn link_token_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_types::pm_auth::LinkTokenCreateRequest>, +) -> impl Responder { + let payload = json_payload.into_inner(); + let flow = Flow::PmAuthLinkTokenCreate; + let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth( + req.headers(), + &payload, + ) { + Ok((auth, _auth_flow)) => (auth, _auth_flow), + Err(e) => return oss_api::log_and_return_error_response(e), + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, payload| { + crate::core::pm_auth::create_link_token( + state, + auth.merchant_account, + auth.key_store, + payload, + ) + }, + &*auth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[instrument(skip_all, fields(flow = ?Flow::PmAuthExchangeToken))] +pub async fn exchange_token( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_types::pm_auth::ExchangeTokenCreateRequest>, +) -> impl Responder { + let payload = json_payload.into_inner(); + let flow = Flow::PmAuthExchangeToken; + let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth( + req.headers(), + &payload, + ) { + Ok((auth, _auth_flow)) => (auth, _auth_flow), + Err(e) => return oss_api::log_and_return_error_response(e), + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, payload| { + crate::core::pm_auth::exchange_token_core( + state, + auth.merchant_account, + auth.key_store, + payload, + ) + }, + &*auth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index e46612b95df..57f3b802bd5 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -6,6 +6,7 @@ pub mod encryption; pub mod jwt; pub mod kafka; pub mod logger; +pub mod pm_auth; #[cfg(feature = "email")] pub mod email; diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 8a0cd7c729e..b48465ebd17 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -641,6 +641,18 @@ impl ClientSecretFetch for api_models::payments::RetrievePaymentLinkRequest { } } +impl ClientSecretFetch for api_models::pm_auth::LinkTokenCreateRequest { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref() + } +} + +impl ClientSecretFetch for api_models::pm_auth::ExchangeTokenCreateRequest { + fn get_client_secret(&self) -> Option<&String> { + self.client_secret.as_ref() + } +} + pub fn get_auth_type_and_flow<A: AppStateInfo + Sync>( headers: &HeaderMap, ) -> RouterResult<( diff --git a/crates/router/src/services/pm_auth.rs b/crates/router/src/services/pm_auth.rs new file mode 100644 index 00000000000..7487b12663b --- /dev/null +++ b/crates/router/src/services/pm_auth.rs @@ -0,0 +1,95 @@ +use pm_auth::{ + consts, + core::errors::ConnectorError, + types::{self as pm_auth_types, api::BoxedConnectorIntegration, PaymentAuthRouterData}, +}; + +use crate::{ + core::errors::{self}, + logger, + routes::AppState, + services::{self}, +}; + +pub async fn execute_connector_processing_step< + 'b, + 'a, + T: 'static, + Req: Clone + 'static, + Resp: Clone + 'static, +>( + state: &'b AppState, + connector_integration: BoxedConnectorIntegration<'a, T, Req, Resp>, + req: &'b PaymentAuthRouterData<T, Req, Resp>, + connector: &pm_auth_types::PaymentMethodAuthConnectors, +) -> errors::CustomResult<PaymentAuthRouterData<T, Req, Resp>, ConnectorError> +where + T: Clone, + Req: Clone, + Resp: Clone, +{ + let mut router_data = req.clone(); + + let connector_request = connector_integration.build_request(req, connector)?; + + match connector_request { + Some(request) => { + logger::debug!(connector_request=?request); + let response = services::api::call_connector_api(state, request).await; + logger::debug!(connector_response=?response); + match response { + Ok(body) => { + let response = match body { + Ok(body) => { + let body = pm_auth_types::Response { + headers: body.headers, + response: body.response, + status_code: body.status_code, + }; + let connector_http_status_code = Some(body.status_code); + let mut data = + connector_integration.handle_response(&router_data, body)?; + data.connector_http_status_code = connector_http_status_code; + + data + } + Err(body) => { + let body = pm_auth_types::Response { + headers: body.headers, + response: body.response, + status_code: body.status_code, + }; + router_data.connector_http_status_code = Some(body.status_code); + + let error = match body.status_code { + 500..=511 => connector_integration.get_5xx_error_response(body)?, + _ => connector_integration.get_error_response(body)?, + }; + + router_data.response = Err(error); + + router_data + } + }; + Ok(response) + } + Err(error) => { + if error.current_context().is_upstream_timeout() { + let error_response = pm_auth_types::ErrorResponse { + code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(), + message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(), + reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()), + status_code: 504, + }; + router_data.response = Err(error_response); + router_data.connector_http_status_code = Some(504); + Ok(router_data) + } else { + Err(error.change_context(ConnectorError::ProcessingStepFailed(None))) + } + } + } + } + None => Ok(router_data), + } +} diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index de28c1a3188..aa563c647ea 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -10,6 +10,8 @@ pub mod api; pub mod domain; #[cfg(feature = "frm")] pub mod fraud_check; +pub mod pm_auth; + pub mod storage; pub mod transformers; diff --git a/crates/router/src/types/pm_auth.rs b/crates/router/src/types/pm_auth.rs new file mode 100644 index 00000000000..e2d08c6afea --- /dev/null +++ b/crates/router/src/types/pm_auth.rs @@ -0,0 +1,38 @@ +use std::str::FromStr; + +use error_stack::{IntoReport, ResultExt}; +use pm_auth::{ + connector::plaid, + types::{ + self as pm_auth_types, + api::{BoxedPaymentAuthConnector, PaymentAuthConnectorData}, + }, +}; + +use crate::core::{ + errors::{self, ApiErrorResponse}, + pm_auth::helpers::PaymentAuthConnectorDataExt, +}; + +impl PaymentAuthConnectorDataExt for PaymentAuthConnectorData { + fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse> { + let connector_name = pm_auth_types::PaymentMethodAuthConnectors::from_str(name) + .into_report() + .change_context(ApiErrorResponse::IncorrectConnectorNameGiven) + .attach_printable_lazy(|| { + format!("unable to parse connector: {:?}", name.to_string()) + })?; + let connector = Self::convert_connector(connector_name.clone())?; + Ok(Self { + connector, + connector_name, + }) + } + fn convert_connector( + connector_name: pm_auth_types::PaymentMethodAuthConnectors, + ) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse> { + match connector_name { + pm_auth_types::PaymentMethodAuthConnectors::Plaid => Ok(Box::new(&plaid::Plaid)), + } + } +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 13ca344e9c5..b682bcb12e6 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -295,6 +295,10 @@ pub enum Flow { UserMerchantAccountList, /// Get users for merchant account GetUserDetails, + /// PaymentMethodAuth Link token create + PmAuthLinkTokenCreate, + /// PaymentMethodAuth Exchange token create + PmAuthExchangeToken, /// Get reset password link ForgotPassword, /// Reset password using link
2023-12-04T10:10:25Z
## Description <!-- Describe your changes in detail --> PM Auth service migration ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
cfafd5cd29857283d57731dda7c5a332a493f531
1. Create merchant account - ``` curl --location --request POST 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "merchant_1701764398", "locker_id": "m0010", "merchant_name": "Sarthak", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "default" } ] }' ``` 2. Create API key 3. Create Plaid Connector account ``` curl --location --request POST 'http://localhost:8080/account/merchant_1701763754/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "payment_method_auth", "connector_name": "plaid", "connector_account_details": { "auth_type": "BodyKey", "api_key": "some key", "key1": "some key" }, "test_mode": false, "disabled": false, "business_country": "US", "business_label":"default", "status": "active", "metadata": { "city": "NY", "unit": "245" } }' ``` 4. Create payment connector account - ``` curl --location --request POST 'http://localhost:8080/account/merchant_1701763754/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "connector_type": "fiz_operations", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "some key" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default", "pm_auth_config": { "enabled_payment_methods": [ { "payment_method": "bank_debit", "payment_method_type": "ach", "connector_name": "plaid", "mca_id": "mca_F6MPzhuQvzhHhOsVdgxi" } ] } }' ``` 5. Payments create - ``` curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O08Uv8O5PjAfrxsSLuduC1bn3FTWEpk0N2vvAKnvhAfc7jISAnrNgkTtcbibjO00' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "business_country": "US", "business_label": "default", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 6. List PM for merchant - ``` curl --location --request GET 'http://localhost:8080/account/payment_methods?client_secret=pay_57JSBXgwKCHdgIyvLXDi_secret_1arVvWIGuP7XlWPMrt8W' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_588a676d99f8470ca0eb3a6d5b955f2a' \ --data-raw '' ``` 7. Link token API - ``` curl --location --request POST 'http://localhost:8080/payment_methods/auth/link' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_588a676d99f8470ca0eb3a6d5b955f2a' \ --data-raw '{ "client_secret": "pay_57JSBXgwKCHdgIyvLXDi_secret_1arVvWIGuP7XlWPMrt8W", "payment_id": "pay_57JSBXgwKCHdgIyvLXDi", "payment_method": "bank_debit", "payment_method_type": "ach" }' ``` 8. Get public token from plaid - ``` curl --location --request POST 'https://sandbox.plaid.com/sandbox/public_token/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_O08Uv8O5PjAfrxsSLuduC1bn3FTWEpk0N2vvAKnvhAfc7jISAnrNgkTtcbibjO00' \ --data-raw '{ "client_id": "some key", "secret": "some key", "institution_id": "ins_20", "initial_products": [ "auth" ], "options": { "webhook": "https://www.genericwebhookurl.com/webhook" } }' ``` 9. Exchange token API - ``` curl --location --request POST 'http://localhost:8080/payment_methods/auth/exchange' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_588a676d99f8470ca0eb3a6d5b955f2a' \ --data-raw '{ "client_secret": "pay_57JSBXgwKCHdgIyvLXDi_secret_1arVvWIGuP7XlWPMrt8W", "public_token": "public-sandbox-19e07c9f-8b96-4e96-81a1-e3e3d5c70dc6", "payment_id": "pay_57JSBXgwKCHdgIyvLXDi", "payment_method": "bank_debit", "payment_method_type": "ach" }' ``` 10. Pm list for customer (take any payment token) - ``` curl --location --request GET 'http://localhost:8080/customers/StripeCustomer/payment_methods' \ --header 'Accept: application/json' \ --header 'api-key: dev_O08Uv8O5PjAfrxsSLuduC1bn3FTWEpk0N2vvAKnvhAfc7jISAnrNgkTtcbibjO00' ``` 11. Payments confirm with payment_token - ``` curl --location --request POST 'http://localhost:8080/payments/pay_57JSBXgwKCHdgIyvLXDi/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_O08Uv8O5PjAfrxsSLuduC1bn3FTWEpk0N2vvAKnvhAfc7jISAnrNgkTtcbibjO00' \ --data-raw '{ "payment_method": "bank_debit", "payment_method_type": "ach", "payment_token": "token_2OqGjTK08Gen3iTEJq6u" }' ```
[ "Cargo.lock", "config/config.example.toml", "config/development.toml", "config/docker_compose.toml", "crates/api_models/Cargo.toml", "crates/api_models/src/enums.rs", "crates/api_models/src/lib.rs", "crates/api_models/src/pm_auth.rs", "crates/pm_auth/Cargo.toml", "crates/pm_auth/README.md", "cra...
juspay/hyperswitch
juspay__hyperswitch-3007
Bug: [Feature]: [Braintree] Sync with Hyperswitch Reference ### :memo: Feature Description - In Hyperswitch, we retrieve transaction status in two ways: 1. Using `transaction_id` which is generated by Connectors 2. Using our `reference_id` which can be passed to Connectors during payment creation - If supported, the request for retrieving Payments and Refunds should use the Hyperswitch's `reference_id`. This would assist in obtaining the payment/refund status in the event we failed to get it due to timeout, connection failure, etc. ### :hammer: Possible Implementation - If the connector supports retrieving payments and refunds using our reference_id i.e `connector_request_reference_id` , we should utilize this functionality instead of exclusively relying on the connector_transaction_id. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2052 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 44daef94e8a..f4bd62add3b 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -228,17 +228,16 @@ impl<F, T> types::PaymentsResponseData, >, ) -> Result<Self, Self::Error> { + let id = item.response.transaction.id.clone(); Ok(Self { status: enums::AttemptStatus::from(item.response.transaction.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.transaction.id, - ), + resource_id: types::ResponseId::ConnectorTransactionId(id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: None, + connector_response_reference_id: Some(id), incremental_authorization_allowed: None, }), ..item.data
2023-12-02T09:33:58Z
## Description fixes #3007 ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
cfafd5cd29857283d57731dda7c5a332a493f531
test case - Make a transaction, in response for reference field, we should see connector transaction id.
[ "crates/router/src/connector/braintree/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2961
Bug: Add connector enums for Routing in add_connector script [BUG] ### Bug Description Recently, routing has been moved to OSS. This change breaks the add_connector script. Connector Enums should be added in euclid enums . ### Expected Behavior after running `bash add_connector.sh <connector-name> <connector-base-url>` code needs to be compiled after template code is created. ### Actual Behavior compilation error before template code is generated because missing connector enums in Routing . ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' run `bash add_connector.sh <connector-name> <connector-base-url>` to create new connector template code .This would throw errors in following files crates/api_models/src/routing.rs:290:30 crates/api_models/src/enums.rs:168:5 ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.lock b/Cargo.lock index e4a317d74f4..2ca33b6910a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2339,6 +2339,7 @@ name = "euclid_wasm" version = "0.1.0" dependencies = [ "api_models", + "common_enums", "currency_conversion", "euclid", "getrandom 0.2.10", @@ -3306,6 +3307,7 @@ name = "kgraph_utils" version = "0.1.0" dependencies = [ "api_models", + "common_enums", "criterion", "euclid", "masking", diff --git a/connector-template/mod.rs b/connector-template/mod.rs index e441b0e5879..e9945a726a9 100644 --- a/connector-template/mod.rs +++ b/connector-template/mod.rs @@ -106,6 +106,7 @@ impl ConnectorCommon for {{project-name | downcase | pascal_case}} { message: response.message, reason: response.reason, attempt_status: None, + connector_transaction_id: None, }) } } @@ -485,7 +486,7 @@ impl api::IncomingWebhook for {{project-name | downcase | pascal_case}} { fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<Box<dyn erased_serde::Serialize>, errors::ConnectorError> { + ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(errors::ConnectorError::WebhooksNotImplemented).into_report() } } diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index ffefaa2ad2c..535be4dfb15 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -147,104 +147,6 @@ impl Connector { } } -#[derive( - Clone, - Copy, - Debug, - Eq, - Hash, - PartialEq, - serde::Serialize, - serde::Deserialize, - strum::Display, - strum::EnumString, - strum::EnumIter, - strum::EnumVariantNames, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum RoutableConnectors { - #[cfg(feature = "dummy_connector")] - #[serde(rename = "phonypay")] - #[strum(serialize = "phonypay")] - DummyConnector1, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "fauxpay")] - #[strum(serialize = "fauxpay")] - DummyConnector2, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "pretendpay")] - #[strum(serialize = "pretendpay")] - DummyConnector3, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "stripe_test")] - #[strum(serialize = "stripe_test")] - DummyConnector4, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "adyen_test")] - #[strum(serialize = "adyen_test")] - DummyConnector5, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "checkout_test")] - #[strum(serialize = "checkout_test")] - DummyConnector6, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "paypal_test")] - #[strum(serialize = "paypal_test")] - DummyConnector7, - Aci, - Adyen, - Airwallex, - Authorizedotnet, - Bankofamerica, - Bitpay, - Bambora, - Bluesnap, - Boku, - Braintree, - Cashtocode, - Checkout, - Coinbase, - Cryptopay, - Cybersource, - Dlocal, - Fiserv, - Forte, - Globalpay, - Globepay, - Gocardless, - Helcim, - Iatapay, - Klarna, - Mollie, - Multisafepay, - Nexinets, - Nmi, - Noon, - Nuvei, - // Opayo, added as template code for future usage - Opennode, - // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage - Payme, - Paypal, - Payu, - Powertranz, - Prophetpay, - Rapyd, - Shift4, - Square, - Stax, - Stripe, - Trustpay, - // Tsys, - Tsys, - Volt, - Wise, - Worldline, - Worldpay, - Zen, -} - #[cfg(feature = "payouts")] #[derive( Clone, diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 47a44ea7443..2236714da1d 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -4,7 +4,6 @@ use common_utils::errors::ParsingError; use error_stack::IntoReport; use euclid::{ dssa::types::EuclidAnalysable, - enums as euclid_enums, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, @@ -287,71 +286,7 @@ impl From<RoutableConnectorChoice> for RoutableChoiceSerde { impl From<RoutableConnectorChoice> for ast::ConnectorChoice { fn from(value: RoutableConnectorChoice) -> Self { Self { - connector: match value.connector { - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector1 => euclid_enums::Connector::DummyConnector1, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector2 => euclid_enums::Connector::DummyConnector2, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector3 => euclid_enums::Connector::DummyConnector3, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector4 => euclid_enums::Connector::DummyConnector4, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector5 => euclid_enums::Connector::DummyConnector5, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector6 => euclid_enums::Connector::DummyConnector6, - #[cfg(feature = "dummy_connector")] - RoutableConnectors::DummyConnector7 => euclid_enums::Connector::DummyConnector7, - RoutableConnectors::Aci => euclid_enums::Connector::Aci, - RoutableConnectors::Adyen => euclid_enums::Connector::Adyen, - RoutableConnectors::Airwallex => euclid_enums::Connector::Airwallex, - RoutableConnectors::Authorizedotnet => euclid_enums::Connector::Authorizedotnet, - RoutableConnectors::Bambora => euclid_enums::Connector::Bambora, - RoutableConnectors::Bankofamerica => euclid_enums::Connector::Bankofamerica, - RoutableConnectors::Bitpay => euclid_enums::Connector::Bitpay, - RoutableConnectors::Bluesnap => euclid_enums::Connector::Bluesnap, - RoutableConnectors::Boku => euclid_enums::Connector::Boku, - RoutableConnectors::Braintree => euclid_enums::Connector::Braintree, - RoutableConnectors::Cashtocode => euclid_enums::Connector::Cashtocode, - RoutableConnectors::Checkout => euclid_enums::Connector::Checkout, - RoutableConnectors::Coinbase => euclid_enums::Connector::Coinbase, - RoutableConnectors::Cryptopay => euclid_enums::Connector::Cryptopay, - RoutableConnectors::Cybersource => euclid_enums::Connector::Cybersource, - RoutableConnectors::Dlocal => euclid_enums::Connector::Dlocal, - RoutableConnectors::Fiserv => euclid_enums::Connector::Fiserv, - RoutableConnectors::Forte => euclid_enums::Connector::Forte, - RoutableConnectors::Globalpay => euclid_enums::Connector::Globalpay, - RoutableConnectors::Globepay => euclid_enums::Connector::Globepay, - RoutableConnectors::Gocardless => euclid_enums::Connector::Gocardless, - RoutableConnectors::Helcim => euclid_enums::Connector::Helcim, - RoutableConnectors::Iatapay => euclid_enums::Connector::Iatapay, - RoutableConnectors::Klarna => euclid_enums::Connector::Klarna, - RoutableConnectors::Mollie => euclid_enums::Connector::Mollie, - RoutableConnectors::Multisafepay => euclid_enums::Connector::Multisafepay, - RoutableConnectors::Nexinets => euclid_enums::Connector::Nexinets, - RoutableConnectors::Nmi => euclid_enums::Connector::Nmi, - RoutableConnectors::Noon => euclid_enums::Connector::Noon, - RoutableConnectors::Nuvei => euclid_enums::Connector::Nuvei, - RoutableConnectors::Opennode => euclid_enums::Connector::Opennode, - RoutableConnectors::Payme => euclid_enums::Connector::Payme, - RoutableConnectors::Paypal => euclid_enums::Connector::Paypal, - RoutableConnectors::Payu => euclid_enums::Connector::Payu, - RoutableConnectors::Powertranz => euclid_enums::Connector::Powertranz, - RoutableConnectors::Prophetpay => euclid_enums::Connector::Prophetpay, - RoutableConnectors::Rapyd => euclid_enums::Connector::Rapyd, - RoutableConnectors::Shift4 => euclid_enums::Connector::Shift4, - RoutableConnectors::Square => euclid_enums::Connector::Square, - RoutableConnectors::Stax => euclid_enums::Connector::Stax, - RoutableConnectors::Stripe => euclid_enums::Connector::Stripe, - RoutableConnectors::Trustpay => euclid_enums::Connector::Trustpay, - RoutableConnectors::Tsys => euclid_enums::Connector::Tsys, - RoutableConnectors::Volt => euclid_enums::Connector::Volt, - RoutableConnectors::Wise => euclid_enums::Connector::Wise, - RoutableConnectors::Worldline => euclid_enums::Connector::Worldline, - RoutableConnectors::Worldpay => euclid_enums::Connector::Worldpay, - RoutableConnectors::Zen => euclid_enums::Connector::Zen, - }, - + connector: value.connector, #[cfg(not(feature = "connector_choice_mca_id"))] sub_label: value.sub_label, } diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml index 88628825ca6..cd061970bff 100644 --- a/crates/common_enums/Cargo.toml +++ b/crates/common_enums/Cargo.toml @@ -7,6 +7,10 @@ rust-version.workspace = true readme = "README.md" license.workspace = true +[features] +default = ["dummy_connector"] +dummy_connector = [] + [dependencies] diesel = { version = "2.1.0", features = ["postgres"] } serde = { version = "1.0.160", features = ["derive"] } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 063e35933c4..3f343965130 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -59,6 +59,105 @@ pub enum AttemptStatus { DeviceDataCollectionPending, } +#[derive( + Clone, + Copy, + Debug, + Eq, + Hash, + PartialEq, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, + strum::EnumIter, + strum::EnumVariantNames, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum RoutableConnectors { + #[cfg(feature = "dummy_connector")] + #[serde(rename = "phonypay")] + #[strum(serialize = "phonypay")] + DummyConnector1, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "fauxpay")] + #[strum(serialize = "fauxpay")] + DummyConnector2, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "pretendpay")] + #[strum(serialize = "pretendpay")] + DummyConnector3, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "stripe_test")] + #[strum(serialize = "stripe_test")] + DummyConnector4, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "adyen_test")] + #[strum(serialize = "adyen_test")] + DummyConnector5, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "checkout_test")] + #[strum(serialize = "checkout_test")] + DummyConnector6, + #[cfg(feature = "dummy_connector")] + #[serde(rename = "paypal_test")] + #[strum(serialize = "paypal_test")] + DummyConnector7, + Aci, + Adyen, + Airwallex, + Authorizedotnet, + Bankofamerica, + Bitpay, + Bambora, + Bluesnap, + Boku, + Braintree, + Cashtocode, + Checkout, + Coinbase, + Cryptopay, + Cybersource, + Dlocal, + Fiserv, + Forte, + Globalpay, + Globepay, + Gocardless, + Helcim, + Iatapay, + Klarna, + Mollie, + Multisafepay, + Nexinets, + Nmi, + Noon, + Nuvei, + // Opayo, added as template code for future usage + Opennode, + // Payeezy, As psync and rsync are not supported by this connector, it is added as template code for future usage + Payme, + Paypal, + Payu, + Powertranz, + Prophetpay, + Rapyd, + Shift4, + Square, + Stax, + Stripe, + Trustpay, + // Tsys, + Tsys, + Volt, + Wise, + Worldline, + Worldpay, + Zen, +} + impl AttemptStatus { pub fn is_terminal_status(self) -> bool { match self { diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rs index dc6d9f66a58..68e081c7aa9 100644 --- a/crates/euclid/src/enums.rs +++ b/crates/euclid/src/enums.rs @@ -1,8 +1,7 @@ pub use common_enums::{ AuthenticationType, CaptureMethod, CardNetwork, Country, Currency, - FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType, + FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType, RoutableConnectors, }; -use serde::{Deserialize, Serialize}; use strum::VariantNames; pub trait CollectVariants { @@ -24,6 +23,7 @@ macro_rules! collect_variants { pub(crate) use collect_variants; collect_variants!(PaymentMethod); +collect_variants!(RoutableConnectors); collect_variants!(PaymentType); collect_variants!(MandateType); collect_variants!(MandateAcceptanceType); @@ -33,105 +33,8 @@ collect_variants!(AuthenticationType); collect_variants!(CaptureMethod); collect_variants!(Currency); collect_variants!(Country); -collect_variants!(Connector); collect_variants!(SetupFutureUsage); -#[derive( - Debug, - Copy, - Clone, - PartialEq, - Eq, - Hash, - Serialize, - Deserialize, - strum::Display, - strum::EnumVariantNames, - strum::EnumIter, - strum::EnumString, - frunk::LabelledGeneric, -)] -#[serde(rename_all = "snake_case")] -#[strum(serialize_all = "snake_case")] -pub enum Connector { - #[cfg(feature = "dummy_connector")] - #[serde(rename = "phonypay")] - #[strum(serialize = "phonypay")] - DummyConnector1, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "fauxpay")] - #[strum(serialize = "fauxpay")] - DummyConnector2, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "pretendpay")] - #[strum(serialize = "pretendpay")] - DummyConnector3, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "stripe_test")] - #[strum(serialize = "stripe_test")] - DummyConnector4, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "adyen_test")] - #[strum(serialize = "adyen_test")] - DummyConnector5, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "checkout_test")] - #[strum(serialize = "checkout_test")] - DummyConnector6, - #[cfg(feature = "dummy_connector")] - #[serde(rename = "paypal_test")] - #[strum(serialize = "paypal_test")] - DummyConnector7, - Aci, - Adyen, - Airwallex, - Authorizedotnet, - Bambora, - Bankofamerica, - Bitpay, - Bluesnap, - Boku, - Braintree, - Cashtocode, - Checkout, - Coinbase, - Cryptopay, - Cybersource, - Dlocal, - Fiserv, - Forte, - Globalpay, - Globepay, - Gocardless, - Helcim, - Iatapay, - Klarna, - Mollie, - Multisafepay, - Nexinets, - Nmi, - Noon, - Nuvei, - Opennode, - Payme, - Paypal, - Payu, - Powertranz, - Prophetpay, - Rapyd, - Shift4, - Square, - Stax, - Stripe, - Trustpay, - Tsys, - Volt, - Wise, - Worldline, - Worldpay, - Zen, -} - #[derive( Clone, Debug, diff --git a/crates/euclid/src/frontend/ast.rs b/crates/euclid/src/frontend/ast.rs index 3adb06ab187..0dad9b53c32 100644 --- a/crates/euclid/src/frontend/ast.rs +++ b/crates/euclid/src/frontend/ast.rs @@ -2,16 +2,14 @@ pub mod lowering; #[cfg(feature = "ast_parser")] pub mod parser; +use common_enums::RoutableConnectors; use serde::{Deserialize, Serialize}; -use crate::{ - enums::Connector, - types::{DataType, Metadata}, -}; +use crate::types::{DataType, Metadata}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct ConnectorChoice { - pub connector: Connector, + pub connector: RoutableConnectors, #[cfg(not(feature = "connector_choice_mca_id"))] pub sub_label: Option<String>, } diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs index 7f2fc252d23..f8cef1f9295 100644 --- a/crates/euclid/src/frontend/dir.rs +++ b/crates/euclid/src/frontend/dir.rs @@ -13,7 +13,7 @@ macro_rules! dirval { (Connector = $name:ident) => { $crate::frontend::dir::DirValue::Connector(Box::new( $crate::frontend::ast::ConnectorChoice { - connector: $crate::frontend::dir::enums::Connector::$name, + connector: $crate::enums::RoutableConnectors::$name, }, )) }; @@ -51,7 +51,7 @@ macro_rules! dirval { (Connector = $name:ident) => { $crate::frontend::dir::DirValue::Connector(Box::new( $crate::frontend::ast::ConnectorChoice { - connector: $crate::frontend::dir::enums::Connector::$name, + connector: $crate::enums::RoutableConnectors::$name, sub_label: None, }, )) @@ -60,7 +60,7 @@ macro_rules! dirval { (Connector = ($name:ident, $sub_label:literal)) => { $crate::frontend::dir::DirValue::Connector(Box::new( $crate::frontend::ast::ConnectorChoice { - connector: $crate::frontend::dir::enums::Connector::$name, + connector: $crate::enums::RoutableConnectors::$name, sub_label: Some($sub_label.to_string()), }, )) @@ -464,7 +464,7 @@ impl DirKeyKind { .collect(), ), Self::Connector => Some( - enums::Connector::iter() + common_enums::RoutableConnectors::iter() .map(|connector| { DirValue::Connector(Box::new(ast::ConnectorChoice { connector, diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index f049ad35328..0b71f916d03 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -2,9 +2,9 @@ use strum::VariantNames; use crate::enums::collect_variants; pub use crate::enums::{ - AuthenticationType, CaptureMethod, CardNetwork, Connector, Country, Country as BusinessCountry, + AuthenticationType, CaptureMethod, CardNetwork, Country, Country as BusinessCountry, Country as BillingCountry, Currency as PaymentCurrency, MandateAcceptanceType, MandateType, - PaymentMethod, PaymentType, SetupFutureUsage, + PaymentMethod, PaymentType, RoutableConnectors, SetupFutureUsage, }; #[derive( diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index 47e349847ef..8c96a7f67da 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -20,6 +20,7 @@ api_models = { version = "0.1.0", path = "../api_models", package = "api_models" currency_conversion = { version = "0.1.0", path = "../currency_conversion" } euclid = { path = "../euclid", features = [] } kgraph_utils = { version = "0.1.0", path = "../kgraph_utils" } +common_enums = { version = "0.1.0", path = "../common_enums" } # Third party crates getrandom = { version = "0.2.10", features = ["js"] } diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs index 48d9ac0d82a..cab82f8ce41 100644 --- a/crates/euclid_wasm/src/lib.rs +++ b/crates/euclid_wasm/src/lib.rs @@ -7,6 +7,7 @@ use std::{ }; use api_models::{admin as admin_api, routing::ConnectorSelection}; +use common_enums::RoutableConnectors; use currency_conversion::{ conversion::convert as convert_currency, types as currency_conversion_types, }; @@ -17,7 +18,6 @@ use euclid::{ graph::{self, Memoization}, state_machine, truth, }, - enums, frontend::{ ast, dir::{self, enums as dir_enums}, @@ -61,8 +61,8 @@ pub fn convert_forex_value(amount: i64, from_currency: JsValue, to_currency: JsV .get() .ok_or("Forex Data not seeded") .err_to_js()?; - let from_currency: enums::Currency = serde_wasm_bindgen::from_value(from_currency)?; - let to_currency: enums::Currency = serde_wasm_bindgen::from_value(to_currency)?; + let from_currency: common_enums::Currency = serde_wasm_bindgen::from_value(from_currency)?; + let to_currency: common_enums::Currency = serde_wasm_bindgen::from_value(to_currency)?; let converted_amount = convert_currency(forex_data, from_currency, to_currency, amount) .map_err(|_| "conversion not possible for provided values") .err_to_js()?; @@ -80,7 +80,7 @@ pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult { .iter() .map(|mca| { Ok::<_, strum::ParseError>(ast::ConnectorChoice { - connector: dir_enums::Connector::from_str(&mca.connector_name)?, + connector: RoutableConnectors::from_str(&mca.connector_name)?, #[cfg(not(feature = "connector_choice_mca_id"))] sub_label: mca.business_sub_label.clone(), }) @@ -183,7 +183,9 @@ pub fn run_program(program: JsValue, input: JsValue) -> JsResult { #[wasm_bindgen(js_name = getAllConnectors)] pub fn get_all_connectors() -> JsResult { - Ok(serde_wasm_bindgen::to_value(enums::Connector::VARIANTS)?) + Ok(serde_wasm_bindgen::to_value( + common_enums::RoutableConnectors::VARIANTS, + )?) } #[wasm_bindgen(js_name = getAllKeys)] diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml index cd0adf0bc8a..44a73dae4d7 100644 --- a/crates/kgraph_utils/Cargo.toml +++ b/crates/kgraph_utils/Cargo.toml @@ -11,6 +11,7 @@ connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connect [dependencies] api_models = { version = "0.1.0", path = "../api_models", package = "api_models" } +common_enums = { version = "0.1.0", path = "../common_enums" } euclid = { version = "0.1.0", path = "../euclid" } masking = { version = "0.1.0", path = "../masking/" } diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index deea51bd880..0e224a8f3d9 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -5,10 +5,7 @@ use api_models::{ }; use euclid::{ dssa::graph::{self, DomainIdentifier}, - frontend::{ - ast, - dir::{self, enums as dir_enums}, - }, + frontend::{ast, dir}, types::{NumValue, NumValueRefinement}, }; @@ -277,7 +274,7 @@ fn compile_merchant_connector_graph( builder: &mut graph::KnowledgeGraphBuilder<'_>, mca: admin_api::MerchantConnectorResponse, ) -> Result<(), KgraphError> { - let connector = dir_enums::Connector::from_str(&mca.connector_name) + let connector = common_enums::RoutableConnectors::from_str(&mca.connector_name) .map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name.clone()))?; let mut agg_nodes: Vec<(graph::NodeId, graph::Relation)> = Vec::new(); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 1c40ef81f49..d308c98b75d 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -81,7 +81,7 @@ pub async fn payments_operation_core<F, Req, Op, FData, Ctx>( req: Req, call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, - eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>, + eligible_connectors: Option<Vec<common_enums::RoutableConnectors>>, header_payload: HeaderPayload, ) -> RouterResult<( PaymentData<F>, diff --git a/crates/router/src/core/payments/routing/transformers.rs b/crates/router/src/core/payments/routing/transformers.rs index 5704f82f498..b273f18f3fd 100644 --- a/crates/router/src/core/payments/routing/transformers.rs +++ b/crates/router/src/core/payments/routing/transformers.rs @@ -1,15 +1,15 @@ -use api_models::{self, enums as api_enums, routing as routing_types}; +use api_models::{self, routing as routing_types}; use diesel_models::enums as storage_enums; use euclid::{enums as dsl_enums, frontend::ast as dsl_ast}; -use crate::types::transformers::{ForeignFrom, ForeignInto}; +use crate::types::transformers::ForeignFrom; impl ForeignFrom<routing_types::RoutableConnectorChoice> for dsl_ast::ConnectorChoice { fn foreign_from(from: routing_types::RoutableConnectorChoice) -> Self { Self { // #[cfg(feature = "backwards_compatibility")] // choice_kind: from.choice_kind.foreign_into(), - connector: from.connector.foreign_into(), + connector: from.connector, #[cfg(not(feature = "connector_choice_mca_id"))] sub_label: from.sub_label, } @@ -52,72 +52,3 @@ impl ForeignFrom<storage_enums::MandateDataType> for dsl_enums::MandateType { } } } - -impl ForeignFrom<api_enums::RoutableConnectors> for dsl_enums::Connector { - fn foreign_from(from: api_enums::RoutableConnectors) -> Self { - match from { - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector1 => Self::DummyConnector1, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector2 => Self::DummyConnector2, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector3 => Self::DummyConnector3, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector4 => Self::DummyConnector4, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector5 => Self::DummyConnector5, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector6 => Self::DummyConnector6, - #[cfg(feature = "dummy_connector")] - api_enums::RoutableConnectors::DummyConnector7 => Self::DummyConnector7, - api_enums::RoutableConnectors::Aci => Self::Aci, - api_enums::RoutableConnectors::Adyen => Self::Adyen, - api_enums::RoutableConnectors::Airwallex => Self::Airwallex, - api_enums::RoutableConnectors::Authorizedotnet => Self::Authorizedotnet, - api_enums::RoutableConnectors::Bambora => Self::Bambora, - api_enums::RoutableConnectors::Bankofamerica => Self::Bankofamerica, - api_enums::RoutableConnectors::Bitpay => Self::Bitpay, - api_enums::RoutableConnectors::Bluesnap => Self::Bluesnap, - api_enums::RoutableConnectors::Boku => Self::Boku, - api_enums::RoutableConnectors::Braintree => Self::Braintree, - api_enums::RoutableConnectors::Cashtocode => Self::Cashtocode, - api_enums::RoutableConnectors::Checkout => Self::Checkout, - api_enums::RoutableConnectors::Coinbase => Self::Coinbase, - api_enums::RoutableConnectors::Cryptopay => Self::Cryptopay, - api_enums::RoutableConnectors::Cybersource => Self::Cybersource, - api_enums::RoutableConnectors::Dlocal => Self::Dlocal, - api_enums::RoutableConnectors::Fiserv => Self::Fiserv, - api_enums::RoutableConnectors::Forte => Self::Forte, - api_enums::RoutableConnectors::Globalpay => Self::Globalpay, - api_enums::RoutableConnectors::Globepay => Self::Globepay, - api_enums::RoutableConnectors::Gocardless => Self::Gocardless, - api_enums::RoutableConnectors::Helcim => Self::Helcim, - api_enums::RoutableConnectors::Iatapay => Self::Iatapay, - api_enums::RoutableConnectors::Klarna => Self::Klarna, - api_enums::RoutableConnectors::Mollie => Self::Mollie, - api_enums::RoutableConnectors::Multisafepay => Self::Multisafepay, - api_enums::RoutableConnectors::Nexinets => Self::Nexinets, - api_enums::RoutableConnectors::Nmi => Self::Nmi, - api_enums::RoutableConnectors::Noon => Self::Noon, - api_enums::RoutableConnectors::Nuvei => Self::Nuvei, - api_enums::RoutableConnectors::Opennode => Self::Opennode, - api_enums::RoutableConnectors::Payme => Self::Payme, - api_enums::RoutableConnectors::Paypal => Self::Paypal, - api_enums::RoutableConnectors::Payu => Self::Payu, - api_enums::RoutableConnectors::Powertranz => Self::Powertranz, - api_enums::RoutableConnectors::Prophetpay => Self::Prophetpay, - api_enums::RoutableConnectors::Rapyd => Self::Rapyd, - api_enums::RoutableConnectors::Shift4 => Self::Shift4, - api_enums::RoutableConnectors::Square => Self::Square, - api_enums::RoutableConnectors::Stax => Self::Stax, - api_enums::RoutableConnectors::Stripe => Self::Stripe, - api_enums::RoutableConnectors::Trustpay => Self::Trustpay, - api_enums::RoutableConnectors::Tsys => Self::Tsys, - api_enums::RoutableConnectors::Volt => Self::Volt, - api_enums::RoutableConnectors::Wise => Self::Wise, - api_enums::RoutableConnectors::Worldline => Self::Worldline, - api_enums::RoutableConnectors::Worldpay => Self::Worldpay, - api_enums::RoutableConnectors::Zen => Self::Zen, - } - } -} diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 45aad93371e..66a8ba7936d 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -9,7 +9,6 @@ use common_utils::{ }; use diesel_models::enums as storage_enums; use error_stack::{IntoReport, ResultExt}; -use euclid::enums as dsl_enums; use masking::{ExposeInterface, PeekInterface}; use super::domain; @@ -174,25 +173,11 @@ impl ForeignFrom<storage_enums::MandateDataType> for api_models::payments::Manda } } -impl ForeignTryFrom<api_enums::Connector> for api_enums::RoutableConnectors { +impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { type Error = error_stack::Report<common_utils::errors::ValidationError>; fn foreign_try_from(from: api_enums::Connector) -> Result<Self, Self::Error> { Ok(match from { - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector1 => Self::DummyConnector1, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector2 => Self::DummyConnector2, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector3 => Self::DummyConnector3, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector4 => Self::DummyConnector4, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector5 => Self::DummyConnector5, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector6 => Self::DummyConnector6, - #[cfg(feature = "dummy_connector")] - api_enums::Connector::DummyConnector7 => Self::DummyConnector7, api_enums::Connector::Aci => Self::Aci, api_enums::Connector::Adyen => Self::Adyen, api_enums::Connector::Airwallex => Self::Airwallex, @@ -253,76 +238,21 @@ impl ForeignTryFrom<api_enums::Connector> for api_enums::RoutableConnectors { api_enums::Connector::Worldline => Self::Worldline, api_enums::Connector::Worldpay => Self::Worldpay, api_enums::Connector::Zen => Self::Zen, - }) - } -} - -impl ForeignFrom<dsl_enums::Connector> for api_enums::RoutableConnectors { - fn foreign_from(from: dsl_enums::Connector) -> Self { - match from { #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector1 => Self::DummyConnector1, + api_enums::Connector::DummyConnector1 => Self::DummyConnector1, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector2 => Self::DummyConnector2, + api_enums::Connector::DummyConnector2 => Self::DummyConnector2, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector3 => Self::DummyConnector3, + api_enums::Connector::DummyConnector3 => Self::DummyConnector3, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector4 => Self::DummyConnector4, + api_enums::Connector::DummyConnector4 => Self::DummyConnector4, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector5 => Self::DummyConnector5, + api_enums::Connector::DummyConnector5 => Self::DummyConnector5, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector6 => Self::DummyConnector6, + api_enums::Connector::DummyConnector6 => Self::DummyConnector6, #[cfg(feature = "dummy_connector")] - dsl_enums::Connector::DummyConnector7 => Self::DummyConnector7, - dsl_enums::Connector::Aci => Self::Aci, - dsl_enums::Connector::Adyen => Self::Adyen, - dsl_enums::Connector::Airwallex => Self::Airwallex, - dsl_enums::Connector::Authorizedotnet => Self::Authorizedotnet, - dsl_enums::Connector::Bambora => Self::Bambora, - dsl_enums::Connector::Bankofamerica => Self::Bankofamerica, - dsl_enums::Connector::Bitpay => Self::Bitpay, - dsl_enums::Connector::Bluesnap => Self::Bluesnap, - dsl_enums::Connector::Boku => Self::Boku, - dsl_enums::Connector::Braintree => Self::Braintree, - dsl_enums::Connector::Cashtocode => Self::Cashtocode, - dsl_enums::Connector::Checkout => Self::Checkout, - dsl_enums::Connector::Coinbase => Self::Coinbase, - dsl_enums::Connector::Cryptopay => Self::Cryptopay, - dsl_enums::Connector::Cybersource => Self::Cybersource, - dsl_enums::Connector::Dlocal => Self::Dlocal, - dsl_enums::Connector::Fiserv => Self::Fiserv, - dsl_enums::Connector::Forte => Self::Forte, - dsl_enums::Connector::Globalpay => Self::Globalpay, - dsl_enums::Connector::Globepay => Self::Globepay, - dsl_enums::Connector::Gocardless => Self::Gocardless, - dsl_enums::Connector::Helcim => Self::Helcim, - dsl_enums::Connector::Iatapay => Self::Iatapay, - dsl_enums::Connector::Klarna => Self::Klarna, - dsl_enums::Connector::Mollie => Self::Mollie, - dsl_enums::Connector::Multisafepay => Self::Multisafepay, - dsl_enums::Connector::Nexinets => Self::Nexinets, - dsl_enums::Connector::Nmi => Self::Nmi, - dsl_enums::Connector::Noon => Self::Noon, - dsl_enums::Connector::Nuvei => Self::Nuvei, - dsl_enums::Connector::Opennode => Self::Opennode, - dsl_enums::Connector::Payme => Self::Payme, - dsl_enums::Connector::Paypal => Self::Paypal, - dsl_enums::Connector::Payu => Self::Payu, - dsl_enums::Connector::Powertranz => Self::Powertranz, - dsl_enums::Connector::Prophetpay => Self::Prophetpay, - dsl_enums::Connector::Rapyd => Self::Rapyd, - dsl_enums::Connector::Shift4 => Self::Shift4, - dsl_enums::Connector::Square => Self::Square, - dsl_enums::Connector::Stax => Self::Stax, - dsl_enums::Connector::Stripe => Self::Stripe, - dsl_enums::Connector::Trustpay => Self::Trustpay, - dsl_enums::Connector::Tsys => Self::Tsys, - dsl_enums::Connector::Volt => Self::Volt, - dsl_enums::Connector::Wise => Self::Wise, - dsl_enums::Connector::Worldline => Self::Worldline, - dsl_enums::Connector::Worldpay => Self::Worldpay, - dsl_enums::Connector::Zen => Self::Zen, - } + api_enums::Connector::DummyConnector7 => Self::DummyConnector7, + }) } } diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 9a30fe9d757..7ed5e65151e 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -45,7 +45,7 @@ cd $SCRIPT/.. # Remove template files if already created for this connector rm -rf $conn/$payment_gateway $conn/$payment_gateway.rs -git checkout $conn.rs $src/types/api.rs $src/configs/settings.rs config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml crates/api_models/src/enums.rs crates/euclid/src/enums.rs crates/api_models/src/routing.rs $src/core/payments/flows.rs $src/core/admin.rs $src/core/payments/routing/transformers.rs $src/types/transformers.rs +git checkout $conn.rs $src/types/api.rs $src/configs/settings.rs config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml crates/api_models/src/enums.rs crates/euclid/src/enums.rs crates/api_models/src/routing.rs $src/core/payments/flows.rs crates/common_enums/src/enums.rs $src/types/transformers.rs $src/core/admin.rs # Add enum for this connector in required places previous_connector='' @@ -61,14 +61,12 @@ sed -r -i'' -e "s/\"$previous_connector\",/\"$previous_connector\",\n \"${pa sed -i '' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" crates/api_models/src/enums.rs sed -i '' -e "s/\(pub enum Connector {\)/\1\n\t${payment_gateway_camelcase},/" crates/euclid/src/enums.rs sed -i '' -e "s/\(match connector_name {\)/\1\n\t\tapi_enums::Connector::${payment_gateway_camelcase} => {${payment_gateway}::transformers::${payment_gateway_camelcase}AuthType::try_from(val)?;Ok(())}/" $src/core/admin.rs -sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tapi_enums::RoutableConnectors::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/core/payments/routing/transformers.rs -sed -i'' -e "s|dsl_enums::Connector::$previous_connector_camelcase \(.*\)|dsl_enums::Connector::$previous_connector_camelcase \1\n\t\t\tdsl_enums::Connector::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/types/transformers.rs -sed -i'' -e "s|api_enums::Connector::$previous_connector_camelcase \(.*\)|api_enums::Connector::$previous_connector_camelcase \1\n\t\t\tapi_enums::Connector::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/types/transformers.rs -sed -i'' -e "s/\(pub enum RoutableConnectors {\)/\1\n\t${payment_gateway_camelcase},/" crates/api_models/src/enums.rs +sed -i'' -e "s/\(pub enum RoutableConnectors {\)/\1\n\t${payment_gateway_camelcase},/" crates/common_enums/src/enums.rs +sed -i'' -e "s|$previous_connector_camelcase \(.*\)|$previous_connector_camelcase \1\n\t\t\tapi_enums::Connector::${payment_gateway_camelcase} => Self::${payment_gateway_camelcase},|" $src/types/transformers.rs sed -i'' -e "s/^default_imp_for_\(.*\)/default_imp_for_\1\n\tconnector::${payment_gateway_camelcase},/" $src/core/payments/flows.rs # Remove temporary files created in above step -rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/development.toml-e crates/api_models/src/enums.rs-e crates/euclid/src/enums.rs-e crates/api_models/src/routing.rs-e $src/core/payments/flows.rs-e $src/core/admin.rs-e $src/core/payments/routing/transformers.rs-e $src/types/transformers.rs-e +rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/development.toml-e crates/api_models/src/enums.rs-e crates/euclid/src/enums.rs-e crates/api_models/src/routing.rs-e $src/core/payments/flows.rs-e crates/common_enums/src/enums.rs-e $src/types/transformers.rs-e $src/core/admin.rs-e cd $conn/ # Generate template files for the connector
2023-11-28T10:06:59Z
## Description <!-- Describe your changes in detail --> This PR have 2 changes 1)Transferring routable connectors to shared enums will reduce the redundancy associated with employing Euclid enums. 2)fixing connector code template script ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> This PR have 2 changes 1)Transferring routable connectors to shared enums will reduce the redundancy associated with employing Euclid enums. 2)fixing connector code template script #
c0116db271f6afc1b93c04705209bfc346228c68
By running `cargo clippy --all-features --all-targets`
[ "Cargo.lock", "connector-template/mod.rs", "crates/api_models/src/enums.rs", "crates/api_models/src/routing.rs", "crates/common_enums/Cargo.toml", "crates/common_enums/src/enums.rs", "crates/euclid/src/enums.rs", "crates/euclid/src/frontend/ast.rs", "crates/euclid/src/frontend/dir.rs", "crates/euc...
juspay/hyperswitch
juspay__hyperswitch-3001
Bug: [REFACTOR]: Field Type for OpenBankingUk Payment Method ### :memo: Feature Description - In OpenBankingUk, we had two fields issuer and country. As of now these are mandatory fields. But these fields are not required for all the connector, as I came with connector Volt which don't need these fields in their request . ### :hammer: Possible Implementation - We can make this fields optional and handle the cases accordingly for the connectors which already has `open_banking_uk` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? Yes
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index bd4c59211e2..5ecbf795ac5 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1204,10 +1204,10 @@ pub enum BankRedirectData { OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] - issuer: api_enums::BankNames, + issuer: Option<api_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] - country: api_enums::CountryAlpha2, + country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index cfa60111267..4b3fcc85132 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -879,7 +879,126 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer { api::enums::BankNames::TsbBank => Ok(Self::TsbBank), api::enums::BankNames::TescoBank => Ok(Self::TescoBank), api::enums::BankNames::UlsterBank => Ok(Self::UlsterBank), - _ => Err(errors::ConnectorError::NotSupported { + enums::BankNames::AmericanExpress + | enums::BankNames::AffinBank + | enums::BankNames::AgroBank + | enums::BankNames::AllianceBank + | enums::BankNames::AmBank + | enums::BankNames::BankOfAmerica + | enums::BankNames::BankIslam + | enums::BankNames::BankMuamalat + | enums::BankNames::BankRakyat + | enums::BankNames::BankSimpananNasional + | enums::BankNames::BlikPSP + | enums::BankNames::CapitalOne + | enums::BankNames::Chase + | enums::BankNames::Citi + | enums::BankNames::CimbBank + | enums::BankNames::Discover + | enums::BankNames::NavyFederalCreditUnion + | enums::BankNames::PentagonFederalCreditUnion + | enums::BankNames::SynchronyBank + | enums::BankNames::WellsFargo + | enums::BankNames::AbnAmro + | enums::BankNames::AsnBank + | enums::BankNames::Bunq + | enums::BankNames::Handelsbanken + | enums::BankNames::HongLeongBank + | enums::BankNames::Ing + | enums::BankNames::Knab + | enums::BankNames::KuwaitFinanceHouse + | enums::BankNames::Moneyou + | enums::BankNames::Rabobank + | enums::BankNames::Regiobank + | enums::BankNames::SnsBank + | enums::BankNames::TriodosBank + | enums::BankNames::VanLanschot + | enums::BankNames::ArzteUndApothekerBank + | enums::BankNames::AustrianAnadiBankAg + | enums::BankNames::BankAustria + | enums::BankNames::Bank99Ag + | enums::BankNames::BankhausCarlSpangler + | enums::BankNames::BankhausSchelhammerUndSchatteraAg + | enums::BankNames::BankMillennium + | enums::BankNames::BankPEKAOSA + | enums::BankNames::BawagPskAg + | enums::BankNames::BksBankAg + | enums::BankNames::BrullKallmusBankAg + | enums::BankNames::BtvVierLanderBank + | enums::BankNames::CapitalBankGraweGruppeAg + | enums::BankNames::CeskaSporitelna + | enums::BankNames::Dolomitenbank + | enums::BankNames::EasybankAg + | enums::BankNames::EPlatbyVUB + | enums::BankNames::ErsteBankUndSparkassen + | enums::BankNames::FrieslandBank + | enums::BankNames::HypoAlpeadriabankInternationalAg + | enums::BankNames::HypoNoeLbFurNiederosterreichUWien + | enums::BankNames::HypoOberosterreichSalzburgSteiermark + | enums::BankNames::HypoTirolBankAg + | enums::BankNames::HypoVorarlbergBankAg + | enums::BankNames::HypoBankBurgenlandAktiengesellschaft + | enums::BankNames::KomercniBanka + | enums::BankNames::MBank + | enums::BankNames::MarchfelderBank + | enums::BankNames::Maybank + | enums::BankNames::OberbankAg + | enums::BankNames::OsterreichischeArzteUndApothekerbank + | enums::BankNames::OcbcBank + | enums::BankNames::PayWithING + | enums::BankNames::PlaceZIPKO + | enums::BankNames::PlatnoscOnlineKartaPlatnicza + | enums::BankNames::PosojilnicaBankEGen + | enums::BankNames::PostovaBanka + | enums::BankNames::PublicBank + | enums::BankNames::RaiffeisenBankengruppeOsterreich + | enums::BankNames::RhbBank + | enums::BankNames::SchelhammerCapitalBankAg + | enums::BankNames::StandardCharteredBank + | enums::BankNames::SchoellerbankAg + | enums::BankNames::SpardaBankWien + | enums::BankNames::SporoPay + | enums::BankNames::TatraPay + | enums::BankNames::Viamo + | enums::BankNames::VolksbankGruppe + | enums::BankNames::VolkskreditbankAg + | enums::BankNames::VrBankBraunau + | enums::BankNames::UobBank + | enums::BankNames::PayWithAliorBank + | enums::BankNames::BankiSpoldzielcze + | enums::BankNames::PayWithInteligo + | enums::BankNames::BNPParibasPoland + | enums::BankNames::BankNowySA + | enums::BankNames::CreditAgricole + | enums::BankNames::PayWithBOS + | enums::BankNames::PayWithCitiHandlowy + | enums::BankNames::PayWithPlusBank + | enums::BankNames::ToyotaBank + | enums::BankNames::VeloBank + | enums::BankNames::ETransferPocztowy24 + | enums::BankNames::PlusBank + | enums::BankNames::EtransferPocztowy24 + | enums::BankNames::BankiSpbdzielcze + | enums::BankNames::BankNowyBfgSa + | enums::BankNames::GetinBank + | enums::BankNames::Blik + | enums::BankNames::NoblePay + | enums::BankNames::IdeaBank + | enums::BankNames::EnveloBank + | enums::BankNames::NestPrzelew + | enums::BankNames::MbankMtransfer + | enums::BankNames::Inteligo + | enums::BankNames::PbacZIpko + | enums::BankNames::BnpParibas + | enums::BankNames::BankPekaoSa + | enums::BankNames::VolkswagenBank + | enums::BankNames::AliorBank + | enums::BankNames::Boz + | enums::BankNames::BangkokBank + | enums::BankNames::KrungsriBank + | enums::BankNames::KrungThaiBank + | enums::BankNames::TheSiamCommercialBank + | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotSupported { message: String::from("BankRedirect"), connector: "Adyen", })?, @@ -2102,7 +2221,12 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod ), api_models::payments::BankRedirectData::OpenBankingUk { issuer, .. } => Ok( AdyenPaymentMethod::OpenBankingUK(Box::new(OpenBankingUKData { - issuer: OpenBankingUKIssuer::try_from(issuer)?, + issuer: match issuer { + Some(bank_name) => OpenBankingUKIssuer::try_from(bank_name)?, + None => Err(errors::ConnectorError::MissingRequiredField { + field_name: "issuer", + })?, + }, })), ), api_models::payments::BankRedirectData::Sofort { .. } => Ok(AdyenPaymentMethod::Sofort), @@ -2580,7 +2704,7 @@ impl<'a> let additional_data = get_additional_data(item.router_data); let return_url = item.router_data.request.get_return_url()?; let payment_method = AdyenPaymentMethod::try_from(bank_redirect_data)?; - let (shopper_locale, country) = get_redirect_extra_details(item.router_data); + let (shopper_locale, country) = get_redirect_extra_details(item.router_data)?; let line_items = Some(get_line_items(item)); Ok(AdyenPaymentRequest { @@ -2611,7 +2735,7 @@ impl<'a> fn get_redirect_extra_details( item: &types::PaymentsAuthorizeRouterData, -) -> (Option<String>, Option<api_enums::CountryAlpha2>) { +) -> Result<(Option<String>, Option<api_enums::CountryAlpha2>), errors::ConnectorError> { match item.request.payment_method_data { api_models::payments::PaymentMethodData::BankRedirect(ref redirect_data) => { match redirect_data { @@ -2619,17 +2743,20 @@ fn get_redirect_extra_details( country, preferred_language, .. - } => ( + } => Ok(( Some(preferred_language.to_string()), Some(country.to_owned()), - ), + )), api_models::payments::BankRedirectData::OpenBankingUk { country, .. } => { - (None, Some(country.to_owned())) + let country = country.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "country", + })?; + Ok((None, Some(country))) } - _ => (None, None), + _ => Ok((None, None)), } } - _ => (None, None), + _ => Ok((None, None)), } }
2023-11-28T10:01:59Z
## Description In OpenBankingUk, we had two fields issuer and country. But these fields are not required for all the connector, I came with connector Volt which don't need these fields in their request so I made these fields optional. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> # ## Test cases Test ` Open_banking_uk `for Volt and Adyen Coonector. Curl For Open Banking Uk for Adyen: `{ "amount": 6540, "currency": "GBP", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com/", "payment_method": "bank_redirect", "payment_method_type": "open_banking_uk", "payment_method_data": { "bank_redirect": { "open_banking_uk": { "issuer": "open_bank_success", "country": "GB" } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "GB", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "browser_info": { "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true, "ip_address": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "GB", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }`
c05432c0bd70f222c2f898ce2cbb47a46364a490
Using Postman
[ "crates/api_models/src/payments.rs", "crates/router/src/connector/adyen/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2983
Bug: [FEATURE] receive `card_holder_name` in confirm flow when using token for payment ### Feature Description Currently, even though `card_holder_name` was empty, `/confirm` would occur without any error. But few connectors require `card_holder_name` to be sent. ### Possible Implementation Add new object `CardTokenData` in `payment_method_data` object which can be used to send the `card_holder_name` during `/confirm` flow along with the token. The token will fetch the stored card from locker. If this response has a `card_holder_name`, then it proceeds as usual without any error. Else it will check whether any `CardTokenData` object inside `payment_method_data` is sent or not. If not then error is thrown, if present then we update the `card` object received from locker to include the `card_holder_name` passed in `CardTokenData` during `/confirm` flow ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 74559f8ed69..acb9bbdd6cd 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -717,6 +717,14 @@ pub struct Card { pub nick_name: Option<Secret<String>>, } +#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct CardToken { + /// The card holder's name + #[schema(value_type = String, example = "John Test")] + pub card_holder_name: Option<Secret<String>>, +} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { @@ -846,6 +854,7 @@ pub enum PaymentMethodData { Upi(UpiData), Voucher(VoucherData), GiftCard(Box<GiftCardData>), + CardToken(CardToken), } impl PaymentMethodData { @@ -873,7 +882,8 @@ impl PaymentMethodData { | Self::Reward | Self::Upi(_) | Self::Voucher(_) - | Self::GiftCard(_) => None, + | Self::GiftCard(_) + | Self::CardToken(_) => None, } } } @@ -1092,6 +1102,7 @@ pub enum AdditionalPaymentData { GiftCard {}, Voucher {}, CardRedirect {}, + CardToken {}, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] @@ -1660,6 +1671,7 @@ pub enum PaymentMethodDataResponse { Voucher, GiftCard, CardRedirect, + CardToken, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -2455,6 +2467,7 @@ impl From<AdditionalPaymentData> for PaymentMethodDataResponse { AdditionalPaymentData::Voucher {} => Self::Voucher, AdditionalPaymentData::GiftCard {} => Self::GiftCard, AdditionalPaymentData::CardRedirect {} => Self::CardRedirect, + AdditionalPaymentData::CardToken {} => Self::CardToken, } } } diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index f56369ed31a..66aeb3bb6b2 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -409,7 +409,8 @@ impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPayment | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.router_data.payment_method), connector: "Aci", })?, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index a75e3b8ff17..a130ac50cc0 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1380,7 +1380,8 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> payments::PaymentMethodData::Crypto(_) | payments::PaymentMethodData::MandatePayment | payments::PaymentMethodData::Reward - | payments::PaymentMethodData::Upi(_) => { + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Adyen", @@ -2276,7 +2277,8 @@ impl<'a> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: "Network tokenization for payment method".to_string(), connector: "Adyen", diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 457b8d07548..3785e02d474 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -196,7 +196,8 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>> | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("airwallex"), )), }?; diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 70db9a6d879..12170deb1a0 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -410,7 +410,8 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Bank of America"), ) diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index fe92c337a01..b4ed314e706 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -221,7 +221,8 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::CardRedirect(_) | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( "Selected payment method via Token flow through bluesnap".to_string(), )) @@ -240,160 +241,160 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly, _ => BluesnapTxnType::AuthCapture, }; - let (payment_method, card_holder_info) = - match item.router_data.request.payment_method_data.clone() { - api::PaymentMethodData::Card(ref ccard) => Ok(( - PaymentMethodDetails::CreditCard(Card { - card_number: ccard.card_number.clone(), - expiration_month: ccard.card_exp_month.clone(), - expiration_year: ccard.get_expiry_year_4_digit(), - security_code: ccard.card_cvc.clone(), - }), - get_card_holder_info( - item.router_data.get_billing_address()?, - item.router_data.request.get_email()?, - )?, - )), - api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { - api_models::payments::WalletData::GooglePay(payment_method_data) => { - let gpay_object = - Encode::<BluesnapGooglePayObject>::encode_to_string_of_json( - &BluesnapGooglePayObject { - payment_method_data: utils::GooglePayWalletData::from( - payment_method_data, - ), - }, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(( - PaymentMethodDetails::Wallet(BluesnapWallet { - wallet_type: BluesnapWalletTypes::GooglePay, - encoded_payment_token: Secret::new( - consts::BASE64_ENGINE.encode(gpay_object), - ), - }), - None, - )) + let (payment_method, card_holder_info) = match item + .router_data + .request + .payment_method_data + .clone() + { + api::PaymentMethodData::Card(ref ccard) => Ok(( + PaymentMethodDetails::CreditCard(Card { + card_number: ccard.card_number.clone(), + expiration_month: ccard.card_exp_month.clone(), + expiration_year: ccard.get_expiry_year_4_digit(), + security_code: ccard.card_cvc.clone(), + }), + get_card_holder_info( + item.router_data.get_billing_address()?, + item.router_data.request.get_email()?, + )?, + )), + api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { + api_models::payments::WalletData::GooglePay(payment_method_data) => { + let gpay_object = Encode::<BluesnapGooglePayObject>::encode_to_string_of_json( + &BluesnapGooglePayObject { + payment_method_data: utils::GooglePayWalletData::from( + payment_method_data, + ), + }, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(( + PaymentMethodDetails::Wallet(BluesnapWallet { + wallet_type: BluesnapWalletTypes::GooglePay, + encoded_payment_token: Secret::new( + consts::BASE64_ENGINE.encode(gpay_object), + ), + }), + None, + )) + } + api_models::payments::WalletData::ApplePay(payment_method_data) => { + let apple_pay_payment_data = payment_method_data + .get_applepay_decoded_payment_data() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data + .expose()[..] + .as_bytes() + .parse_struct("ApplePayEncodedPaymentData") + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let billing = item + .router_data + .address + .billing + .to_owned() + .get_required_value("billing") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "billing", + })?; + + let billing_address = billing + .address + .get_required_value("billing_address") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "billing", + })?; + + let mut address = Vec::new(); + if let Some(add) = billing_address.line1.to_owned() { + address.push(add) } - api_models::payments::WalletData::ApplePay(payment_method_data) => { - let apple_pay_payment_data = payment_method_data - .get_applepay_decoded_payment_data() - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - let apple_pay_payment_data: ApplePayEncodedPaymentData = - apple_pay_payment_data.expose()[..] - .as_bytes() - .parse_struct("ApplePayEncodedPaymentData") - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - let billing = item - .router_data - .address - .billing - .to_owned() - .get_required_value("billing") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "billing", - })?; - - let billing_address = billing - .address - .get_required_value("billing_address") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "billing", - })?; - - let mut address = Vec::new(); - if let Some(add) = billing_address.line1.to_owned() { - address.push(add) - } - if let Some(add) = billing_address.line2.to_owned() { - address.push(add) - } - if let Some(add) = billing_address.line3.to_owned() { - address.push(add) - } - - let apple_pay_object = - Encode::<EncodedPaymentToken>::encode_to_string_of_json( - &EncodedPaymentToken { - token: ApplepayPaymentData { - payment_data: apple_pay_payment_data, - payment_method: payment_method_data - .payment_method - .to_owned() - .into(), - transaction_identifier: payment_method_data - .transaction_identifier, - }, - billing_contact: BillingDetails { - country_code: billing_address.country, - address_lines: Some(address), - family_name: billing_address.last_name.to_owned(), - given_name: billing_address.first_name.to_owned(), - postal_code: billing_address.zip, - }, - }, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - Ok(( - PaymentMethodDetails::Wallet(BluesnapWallet { - wallet_type: BluesnapWalletTypes::ApplePay, - encoded_payment_token: Secret::new( - consts::BASE64_ENGINE.encode(apple_pay_object), - ), - }), - get_card_holder_info( - item.router_data.get_billing_address()?, - item.router_data.request.get_email()?, - )?, - )) + if let Some(add) = billing_address.line2.to_owned() { + address.push(add) } - payments::WalletData::AliPayQr(_) - | payments::WalletData::AliPayRedirect(_) - | payments::WalletData::AliPayHkRedirect(_) - | payments::WalletData::MomoRedirect(_) - | payments::WalletData::KakaoPayRedirect(_) - | payments::WalletData::GoPayRedirect(_) - | payments::WalletData::GcashRedirect(_) - | payments::WalletData::ApplePayRedirect(_) - | payments::WalletData::ApplePayThirdPartySdk(_) - | payments::WalletData::DanaRedirect {} - | payments::WalletData::GooglePayRedirect(_) - | payments::WalletData::GooglePayThirdPartySdk(_) - | payments::WalletData::MbWayRedirect(_) - | payments::WalletData::MobilePayRedirect(_) - | payments::WalletData::PaypalRedirect(_) - | payments::WalletData::PaypalSdk(_) - | payments::WalletData::SamsungPay(_) - | payments::WalletData::TwintRedirect {} - | payments::WalletData::VippsRedirect {} - | payments::WalletData::TouchNGoRedirect(_) - | payments::WalletData::WeChatPayRedirect(_) - | payments::WalletData::CashappQr(_) - | payments::WalletData::SwishQr(_) - | payments::WalletData::WeChatPayQr(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("bluesnap"), - )) + if let Some(add) = billing_address.line3.to_owned() { + address.push(add) } - }, - payments::PaymentMethodData::PayLater(_) - | payments::PaymentMethodData::BankRedirect(_) - | payments::PaymentMethodData::BankDebit(_) - | payments::PaymentMethodData::BankTransfer(_) - | payments::PaymentMethodData::Crypto(_) - | payments::PaymentMethodData::MandatePayment - | payments::PaymentMethodData::Reward - | payments::PaymentMethodData::Upi(_) - | payments::PaymentMethodData::CardRedirect(_) - | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + + let apple_pay_object = Encode::<EncodedPaymentToken>::encode_to_string_of_json( + &EncodedPaymentToken { + token: ApplepayPaymentData { + payment_data: apple_pay_payment_data, + payment_method: payment_method_data + .payment_method + .to_owned() + .into(), + transaction_identifier: payment_method_data.transaction_identifier, + }, + billing_contact: BillingDetails { + country_code: billing_address.country, + address_lines: Some(address), + family_name: billing_address.last_name.to_owned(), + given_name: billing_address.first_name.to_owned(), + postal_code: billing_address.zip, + }, + }, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + Ok(( + PaymentMethodDetails::Wallet(BluesnapWallet { + wallet_type: BluesnapWalletTypes::ApplePay, + encoded_payment_token: Secret::new( + consts::BASE64_ENGINE.encode(apple_pay_object), + ), + }), + get_card_holder_info( + item.router_data.get_billing_address()?, + item.router_data.request.get_email()?, + )?, + )) + } + payments::WalletData::AliPayQr(_) + | payments::WalletData::AliPayRedirect(_) + | payments::WalletData::AliPayHkRedirect(_) + | payments::WalletData::MomoRedirect(_) + | payments::WalletData::KakaoPayRedirect(_) + | payments::WalletData::GoPayRedirect(_) + | payments::WalletData::GcashRedirect(_) + | payments::WalletData::ApplePayRedirect(_) + | payments::WalletData::ApplePayThirdPartySdk(_) + | payments::WalletData::DanaRedirect {} + | payments::WalletData::GooglePayRedirect(_) + | payments::WalletData::GooglePayThirdPartySdk(_) + | payments::WalletData::MbWayRedirect(_) + | payments::WalletData::MobilePayRedirect(_) + | payments::WalletData::PaypalRedirect(_) + | payments::WalletData::PaypalSdk(_) + | payments::WalletData::SamsungPay(_) + | payments::WalletData::TwintRedirect {} + | payments::WalletData::VippsRedirect {} + | payments::WalletData::TouchNGoRedirect(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::CashappQr(_) + | payments::WalletData::SwishQr(_) + | payments::WalletData::WeChatPayQr(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("bluesnap"), )) } - }?; + }, + payments::PaymentMethodData::PayLater(_) + | payments::PaymentMethodData::BankRedirect(_) + | payments::PaymentMethodData::BankDebit(_) + | payments::PaymentMethodData::BankTransfer(_) + | payments::PaymentMethodData::Crypto(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::Reward + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::Voucher(_) + | payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("bluesnap"), + )), + }?; Ok(Self { amount: item.amount.to_owned(), payment_method, diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs index 5069a9fe38d..009177e961e 100644 --- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs +++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs @@ -138,7 +138,8 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>> | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("braintree"), ) @@ -879,12 +880,11 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest { | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("braintree"), - ) - .into()) - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("braintree"), + ) + .into()), } } } @@ -1423,9 +1423,10 @@ fn get_braintree_redirect_form( | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => Err( - errors::ConnectorError::NotImplemented("given payment method".to_owned()), - )?, + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + "given payment method".to_owned(), + ))?, }, }) } diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 90e65c8b047..173ac0b8f58 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -138,7 +138,8 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::CardRedirect(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("checkout"), ) @@ -375,11 +376,10 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::CardRedirect(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("checkout"), - )) - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("checkout"), + )), }?; let three_ds = match item.router_data.auth_type { diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 0bc4ff3b3ae..446da0761d1 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -80,7 +80,8 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> | api_models::payments::PaymentMethodData::Reward {} | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "CryptoPay", diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 33b8fa56d00..656c45b6d6b 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -367,7 +367,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Cybersource"), ))? diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 668a335cce8..a9033e53d66 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -168,7 +168,8 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( crate::connector::utils::get_unimplemented_payment_method_error_message("Dlocal"), ))?, } diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index dd78324c9b8..2197b4558a2 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -112,7 +112,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { | api_models::payments::PaymentMethodData::Reward {} | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Forte", diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index 72204b51151..63e199657af 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -108,7 +108,8 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for GocardlessCustomerRequest | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Gocardless"), )) @@ -297,12 +298,11 @@ impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount { | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Gocardless"), - ) - .into()) - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Gocardless"), + ) + .into()), } } } @@ -483,11 +483,10 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest { | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotImplemented( - "Setup Mandate flow for selected payment method through Gocardless".to_string(), - )) - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + "Setup Mandate flow for selected payment method through Gocardless".to_string(), + )), }?; let payment_method_token = item.get_payment_method_token()?; let customer_bank_account = match payment_method_token { diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index 9510ff6e67a..9f405e2e2ea 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -141,7 +141,8 @@ impl TryFrom<&types::SetupMandateRouterData> for HelcimVerifyRequest { | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "Helcim", @@ -223,12 +224,11 @@ impl TryFrom<&HelcimRouterData<&types::PaymentsAuthorizeRouterData>> for HelcimP | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { - Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.router_data.request.payment_method_data), - connector: "Helcim", - })? - } + | api_models::payments::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { + message: format!("{:?}", item.router_data.request.payment_method_data), + connector: "Helcim", + })?, } } } diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 3bd3407c3ae..91eaf94c01e 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -406,7 +406,8 @@ impl | api_payments::PaymentMethodData::Reward | api_payments::PaymentMethodData::Upi(_) | api_payments::PaymentMethodData::Voucher(_) - | api_payments::PaymentMethodData::GiftCard(_) => Err(error_stack::report!( + | api_payments::PaymentMethodData::GiftCard(_) + | api_payments::PaymentMethodData::CardToken(_) => Err(error_stack::report!( errors::ConnectorError::MismatchedPaymentData )), } diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index a067818b743..1780b77379c 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -365,7 +365,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }; @@ -509,7 +510,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("multisafepay"), ))?, }; diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 2af3ee0a1bb..15cbe9a7e28 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -624,7 +624,8 @@ fn get_payment_details_and_product( | PaymentMethodData::Reward | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) - | PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nexinets"), ))?, } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index c8721d0d8f6..ff3a1e6a1c5 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -188,7 +188,8 @@ impl TryFrom<&api_models::payments::PaymentMethodData> for PaymentMethod { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "nmi", }) diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 5ff92582051..ee3a8ba8c53 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -284,7 +284,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { | api::PaymentMethodData::Reward {} | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => { + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Noon", diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index b79b2c89264..36244b8bc0d 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -856,8 +856,9 @@ impl<F> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::CardRedirect(_) - | payments::PaymentMethodData::GiftCard(_) => { + | payments::PaymentMethodData::CardRedirect(_) + | payments::PaymentMethodData::GiftCard(_) + | payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), ) @@ -1037,6 +1038,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, String)> for NuveiPay | Some(api::PaymentMethodData::CardRedirect(..)) | Some(api::PaymentMethodData::Reward) | Some(api::PaymentMethodData::Upi(..)) + | Some(api::PaymentMethodData::CardToken(..)) | None => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("nuvei"), )), diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index 41bcc1500ed..5e9fb066c78 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -52,7 +52,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Opayo"), ) .into()), diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 817ab43ac71..90c58c3a9bc 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -260,7 +260,8 @@ fn get_payment_method_data( | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Payeezy"), ))?, } diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 092a8b49fd8..e751de20e21 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -431,7 +431,8 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod { | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Upi(_) - | api::PaymentMethodData::Voucher(_) => { + | PaymentMethodData::Voucher(_) + | PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()) } } @@ -666,7 +667,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("payme"), ))?, } @@ -725,6 +727,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { | Some(api::PaymentMethodData::Upi(_)) | Some(api::PaymentMethodData::Voucher(_)) | Some(api::PaymentMethodData::GiftCard(_)) + | Some(api::PaymentMethodData::CardToken(_)) | None => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } @@ -761,7 +764,8 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => { + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into()) } } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index d023077ff00..e59ff09a1f6 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -584,7 +584,8 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP } api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Crypto(_) - | api_models::payments::PaymentMethodData::Upi(_) => { + | api_models::payments::PaymentMethodData::Upi(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Paypal", diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs index 7f62c1939c0..a631a126ed3 100644 --- a/crates/router/src/connector/powertranz/transformers.rs +++ b/crates/router/src/connector/powertranz/transformers.rs @@ -113,7 +113,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "powertranz", }) diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 0dd3b858349..c272a5b6fc1 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -166,11 +166,14 @@ impl<T> TryFrom<&types::RouterData<T, types::PaymentsAuthorizeData, types::Payme | payments::PaymentMethodData::Crypto(_) | payments::PaymentMethodData::MandatePayment | payments::PaymentMethodData::Reward - | payments::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", + | payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::CardToken(_) => { + Err(errors::ConnectorError::NotSupported { + message: utils::SELECTED_PAYMENT_METHOD.to_string(), + connector: "Shift4", + } + .into()) } - .into()), } } } @@ -397,6 +400,7 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme | Some(payments::PaymentMethodData::Voucher(_)) | Some(payments::PaymentMethodData::Reward) | Some(payments::PaymentMethodData::Upi(_)) + | Some(api::PaymentMethodData::CardToken(_)) | None => Err(errors::ConnectorError::NotSupported { message: "Flow".to_string(), connector: "Shift4", diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index dfb49e8e677..6024a20fa6a 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -191,7 +191,8 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { | api::PaymentMethodData::MandatePayment | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "Square", })?, @@ -307,7 +308,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { | api::PaymentMethodData::MandatePayment | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: format!("{:?}", item.request.payment_method_data), connector: "Square", })?, diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index f2aae442ddd..bb37bf1fc9e 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -118,7 +118,8 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme | api::PaymentMethodData::Voucher(_) | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) - | api::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: "SELECTED_PAYMENT_METHOD".to_string(), connector: "Stax", })?, @@ -268,7 +269,8 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { | api::PaymentMethodData::Voucher(_) | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) - | api::PaymentMethodData::Upi(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: "SELECTED_PAYMENT_METHOD".to_string(), connector: "Stax", })?, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 56eebc2df3b..ae7fe59be96 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1431,13 +1431,13 @@ fn create_stripe_payment_method( .into()), }, - payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::MandatePayment => { - Err(errors::ConnectorError::NotSupported { - message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), - connector: "stripe", - } - .into()) + payments::PaymentMethodData::Upi(_) + | payments::PaymentMethodData::MandatePayment + | payments::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { + message: connector_util::SELECTED_PAYMENT_METHOD.to_string(), + connector: "stripe", } + .into()), } } @@ -2995,6 +2995,7 @@ impl TryFrom<&types::PaymentsPreProcessingRouterData> for StripeCreditTransferSo | Some(payments::PaymentMethodData::GiftCard(..)) | Some(payments::PaymentMethodData::CardRedirect(..)) | Some(payments::PaymentMethodData::Voucher(..)) + | Some(payments::PaymentMethodData::CardToken(..)) | None => Err(errors::ConnectorError::NotImplemented( connector_util::get_unimplemented_payment_method_error_message("stripe"), ) @@ -3416,7 +3417,8 @@ impl | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::CardRedirect(_) - | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { message: format!("{pm_type:?}"), connector: "Stripe", })?, diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 0210d3ca2d9..e891501d6d0 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -445,7 +445,8 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("trustpay"), ) .into()), diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs index c60aeb64898..863b754fc89 100644 --- a/crates/router/src/connector/tsys/transformers.rs +++ b/crates/router/src/connector/tsys/transformers.rs @@ -77,7 +77,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("tsys"), ))?, } diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index e603ef2db06..efed7c797c7 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -148,7 +148,8 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | api_models::payments::PaymentMethodData::Reward | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotSupported { message: utils::SELECTED_PAYMENT_METHOD.to_string(), connector: "Volt", diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 049453e325a..282e1b3a8ad 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -257,7 +257,8 @@ impl | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + | api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldline"), ))?, }; diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index d31f4d65e78..e35a51552c0 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -120,7 +120,8 @@ fn fetch_payment_instrument( | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::CardRedirect(_) - | api_models::payments::PaymentMethodData::GiftCard(_) => { + | api_models::payments::PaymentMethodData::GiftCard(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("worldpay"), ) diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index 689894176b2..64f6d5bf1a0 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -707,7 +707,8 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment api_models::payments::PaymentMethodData::Crypto(_) | api_models::payments::PaymentMethodData::MandatePayment | api_models::payments::PaymentMethodData::Reward - | api_models::payments::PaymentMethodData::Upi(_) => { + | api_models::payments::PaymentMethodData::Upi(_) + | api_models::payments::PaymentMethodData::CardToken(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Zen"), ))? diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 80cec01e916..1049137a947 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -3,6 +3,7 @@ pub mod surcharge_decision_configs; pub mod transformers; pub mod vault; +use api_models::payments::CardToken; pub use api_models::{ enums::{Connector, PayoutConnectors}, payouts as payout_types, @@ -42,6 +43,7 @@ pub trait PaymentMethodRetrieve { token: &storage::PaymentTokenData, payment_intent: &PaymentIntent, card_cvc: Option<masking::Secret<String>>, + card_token_data: Option<&CardToken>, ) -> RouterResult<Option<(payments::PaymentMethodData, enums::PaymentMethod)>>; } @@ -125,6 +127,7 @@ impl PaymentMethodRetrieve for Oss { token_data: &storage::PaymentTokenData, payment_intent: &PaymentIntent, card_cvc: Option<masking::Secret<String>>, + card_token_data: Option<&CardToken>, ) -> RouterResult<Option<(payments::PaymentMethodData, enums::PaymentMethod)>> { match token_data { storage::PaymentTokenData::TemporaryGeneric(generic_token) => { @@ -134,6 +137,7 @@ impl PaymentMethodRetrieve for Oss { payment_intent, card_cvc, merchant_key_store, + card_token_data, ) .await } @@ -145,6 +149,7 @@ impl PaymentMethodRetrieve for Oss { payment_intent, card_cvc, merchant_key_store, + card_token_data, ) .await } @@ -155,6 +160,7 @@ impl PaymentMethodRetrieve for Oss { &card_token.token, payment_intent, card_cvc, + card_token_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) @@ -166,6 +172,7 @@ impl PaymentMethodRetrieve for Oss { &card_token.token, payment_intent, card_cvc, + card_token_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card))) diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index f57c0640f1a..68b8128d790 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use api_models::payments::GetPaymentMethodType; +use api_models::payments::{CardToken, GetPaymentMethodType}; use base64::Engine; use common_utils::{ ext_traits::{AsyncExt, ByteSliceExt, ValueExt}, @@ -1356,6 +1356,7 @@ pub async fn retrieve_payment_method_with_temporary_token( payment_intent: &PaymentIntent, card_cvc: Option<masking::Secret<String>>, merchant_key_store: &domain::MerchantKeyStore, + card_token_data: Option<&CardToken>, ) -> RouterResult<Option<(api::PaymentMethodData, enums::PaymentMethod)>> { let (pm, supplementary_data) = vault::Vault::get_payment_method_data_from_locker(state, token, merchant_key_store) @@ -1375,9 +1376,29 @@ pub async fn retrieve_payment_method_with_temporary_token( Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match pm { Some(api::PaymentMethodData::Card(card)) => { + let mut updated_card = card.clone(); + let mut is_card_updated = false; + + let name_on_card = if card.card_holder_name.clone().expose().is_empty() { + card_token_data + .and_then(|token_data| { + is_card_updated = true; + token_data.card_holder_name.clone() + }) + .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "card_holder_name", + })? + } else { + card.card_holder_name.clone() + }; + updated_card.card_holder_name = name_on_card; + if let Some(cvc) = card_cvc { - let mut updated_card = card; + is_card_updated = true; updated_card.card_cvc = cvc; + } + if is_card_updated { let updated_pm = api::PaymentMethodData::Card(updated_card); vault::Vault::store_payment_method_data_in_locker( state, @@ -1423,6 +1444,7 @@ pub async fn retrieve_card_with_permanent_token( token: &str, payment_intent: &PaymentIntent, card_cvc: Option<masking::Secret<String>>, + card_token_data: Option<&CardToken>, ) -> RouterResult<api::PaymentMethodData> { let customer_id = payment_intent .customer_id @@ -1437,13 +1459,26 @@ pub async fn retrieve_card_with_permanent_token( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker")?; + let name = card + .name_on_card + .get_required_value("name_on_card") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("card holder name was not saved in permanent locker")?; + + let name_on_card = if name.clone().expose().is_empty() { + card_token_data + .and_then(|token_data| token_data.card_holder_name.clone()) + .filter(|name_on_card| !name_on_card.clone().expose().is_empty()) + .ok_or(errors::ApiErrorResponse::MissingRequiredField { + field_name: "card_holder_name", + })? + } else { + name + }; + let api_card = api::Card { card_number: card.card_number, - card_holder_name: card - .name_on_card - .get_required_value("name_on_card") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("card holder name was not saved in permanent locker")?, + card_holder_name: name_on_card, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_cvc: card_cvc.unwrap_or_default(), @@ -1529,6 +1564,11 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>( let card_cvc = payment_data.card_cvc.clone(); + let card_token_data = request.as_ref().and_then(|pmd| match pmd { + api_models::payments::PaymentMethodData::CardToken(token_data) => Some(token_data), + _ => None, + }); + // TODO: Handle case where payment method and token both are present in request properly. let payment_method = match (request, hyperswitch_token) { (_, Some(hyperswitch_token)) => { @@ -1538,6 +1578,7 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>( &hyperswitch_token, &payment_data.payment_intent, card_cvc, + card_token_data, ) .await .attach_printable("in 'make_pm_data'")?; @@ -3316,6 +3357,9 @@ pub async fn get_additional_payment_data( api_models::payments::PaymentMethodData::GiftCard(_) => { api_models::payments::AdditionalPaymentData::GiftCard {} } + api_models::payments::PaymentMethodData::CardToken(_) => { + api_models::payments::AdditionalPaymentData::CardToken {} + } } } @@ -3615,6 +3659,12 @@ pub fn get_key_params_for_surcharge_details( gift_card.get_payment_method_type(), None, )), + api_models::payments::PaymentMethodData::CardToken(_) => { + Err(errors::ApiErrorResponse::InvalidDataValue { + field_name: "payment_method_data", + } + .into()) + } } } diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index d191890b8cd..ec38389cdc4 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -248,6 +248,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::OnlineMandate, api_models::payments::Card, api_models::payments::CardRedirectData, + api_models::payments::CardToken, api_models::payments::CustomerAcceptance, api_models::payments::PaymentsRequest, api_models::payments::PaymentsCreateRequest, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 45aad93371e..5bd28db3c15 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -522,7 +522,8 @@ impl ForeignTryFrom<api_models::payments::PaymentMethodData> for api_enums::Paym payment_method_data: api_models::payments::PaymentMethodData, ) -> Result<Self, Self::Error> { match payment_method_data { - api_models::payments::PaymentMethodData::Card(..) => Ok(Self::Card), + api_models::payments::PaymentMethodData::Card(..) + | api_models::payments::PaymentMethodData::CardToken(..) => Ok(Self::Card), api_models::payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet), api_models::payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater), api_models::payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect), diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 88a0d115ff0..08f41578296 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4053,6 +4053,19 @@ } ] }, + "CardToken": { + "type": "object", + "required": [ + "card_holder_name" + ], + "properties": { + "card_holder_name": { + "type": "string", + "description": "The card holder's name", + "example": "John Test" + } + } + }, "CashappQr": { "type": "object" }, @@ -8657,6 +8670,17 @@ "$ref": "#/components/schemas/GiftCardData" } } + }, + { + "type": "object", + "required": [ + "card_token" + ], + "properties": { + "card_token": { + "$ref": "#/components/schemas/CardToken" + } + } } ] },
2023-11-25T14:20:31Z
## Description <!-- Describe your changes in detail --> Currently, even though `card_holder_name` was empty, `/confirm` would occur without any error. But few connectors require `card_holder_name` to be sent. This PR includes changes for adding new object `CardToken` in `payment_method_data` object which can be used to send the `card_holder_name` during `/confirm` flow along with the token. The token will fetch the stored card from locker. If this response has a `card_holder_name`, then it proceeds as usual without any error. Else it will check whether any `CardToken` object inside `payment_method_data` is sent or not. If not then error is thrown, if present then we update the `card` object received from locker to include the `card_holder_name` passed in `CardToken` during `/confirm` flow ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
0e66b1b5dcce6dd87c9d743c9eb73d0cd8e330b2
1. Make a payment with saving the card. pass card_holder_name empty while saving ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_u67d5zdpJVfHQ5jRhWXNg5F0Wy8MhzG2STAeHBhIKJowJJxAuVtvwhB2lsL427C8' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "business_label": "default", "business_country": "US" }' ``` 2. Do `list_customer_payment_method` to get the `payment_token` 3. Now when you use that token to do payment again, you will get below error ![image](https://github.com/juspay/hyperswitch/assets/70657455/e4cfbd6b-a0fd-4e76-89d7-853a39fe1f78) 4. Now pass the `payment_method_data` object passing the `card_holder_name` here along with token in confirm call ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_u67d5zdpJVfHQ5jRhWXNg5F0Wy8MhzG2STAeHBhIKJowJJxAuVtvwhB2lsL427C8' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_token": "token_PLmf9CALewF4hxRSCkC4", "payment_method_data": { "card_token": { "card_holder_name": "Joseph" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "business_label": "default", "business_country": "US" }' ``` If you see the response from confirm call, the `payment_method_data` object will have the `card_holder_name` passed above ![image](https://github.com/juspay/hyperswitch/assets/70657455/fdba9c8b-b1d9-4ee9-ad0f-0f0cdb7bf2ed)
[ "crates/api_models/src/payments.rs", "crates/router/src/connector/aci/transformers.rs", "crates/router/src/connector/adyen/transformers.rs", "crates/router/src/connector/airwallex/transformers.rs", "crates/router/src/connector/bankofamerica/transformers.rs", "crates/router/src/connector/bluesnap/transform...
juspay/hyperswitch
juspay__hyperswitch-2865
Bug: [REFACTOR] : [Wise] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rs index c481f0c7343..e0fc05c3c89 100644 --- a/crates/router/src/connector/wise/transformers.rs +++ b/crates/router/src/connector/wise/transformers.rs @@ -11,7 +11,7 @@ type Error = error_stack::Report<errors::ConnectorError>; #[cfg(feature = "payouts")] use crate::{ - connector::utils::RouterData, + connector::utils::{self, RouterData}, types::{ api::payouts, storage::enums::{self as storage_enums, PayoutEntityType}, @@ -344,10 +344,9 @@ fn get_payout_bank_details( bic: b.bic, ..WiseBankDetails::default() }), - _ => Err(errors::ConnectorError::NotSupported { - message: "Card payout creation is not supported".to_string(), - connector: "Wise", - }), + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, } } @@ -371,10 +370,9 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WiseRecipientCreateRequest { }), }?; match request.payout_type.to_owned() { - storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported { - message: "Card payout creation is not supported".to_string(), - connector: "Wise", - })?, + storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, storage_enums::PayoutType::Bank => { let account_holder_name = customer_details .ok_or(errors::ConnectorError::MissingRequiredField { @@ -432,10 +430,9 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutQuoteRequest { target_currency: request.destination_currency.to_string(), pay_out: WisePayOutOption::default(), }), - storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported { - message: "Card payout fulfillment is not supported".to_string(), - connector: "Wise", - })?, + storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, } } } @@ -489,10 +486,9 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutCreateRequest { details: wise_transfer_details, }) } - storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported { - message: "Card payout fulfillment is not supported".to_string(), - connector: "Wise", - })?, + storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, } } } @@ -533,10 +529,9 @@ impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutFulfillRequest { storage_enums::PayoutType::Bank => Ok(Self { fund_type: FundType::default(), }), - storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotSupported { - message: "Card payout fulfillment is not supported".to_string(), - connector: "Wise", - })?, + storage_enums::PayoutType::Card => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ))?, } } } @@ -599,10 +594,9 @@ impl TryFrom<PayoutMethodData> for RecipientType { PayoutMethodData::Bank(api_models::payouts::Bank::Ach(_)) => Ok(Self::Aba), PayoutMethodData::Bank(api_models::payouts::Bank::Bacs(_)) => Ok(Self::SortCode), PayoutMethodData::Bank(api_models::payouts::Bank::Sepa(_)) => Ok(Self::Iban), - _ => Err(errors::ConnectorError::NotSupported { - message: "Requested payout_method_type is not supported".to_string(), - connector: "Wise", - } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Wise"), + ) .into()), } }
2023-11-22T14:59:35Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
6c15fc312345ed9520accb4d02b12688f98ba1a1
[ "crates/router/src/connector/wise/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2866
Bug: [REFACTOR] : [Worldline] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index 6cb8862f69b..049453e325a 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -306,10 +306,9 @@ impl TryFrom<utils::CardIssuer> for Gateway { utils::CardIssuer::Master => Ok(Self::MasterCard), utils::CardIssuer::Discover => Ok(Self::Discover), utils::CardIssuer::Visa => Ok(Self::Visa), - _ => Err(errors::ConnectorError::NotSupported { - message: issuer.to_string(), - connector: "worldline", - } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("worldline"), + ) .into()), } }
2023-11-16T17:13:09Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context resolves #2866 <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
94897d841e25d0be8debdfe1ec674f28848e2ad4
No test cases required. As In this PR only error message have been changed from Not Supported error message to NotImplemented error message.
[ "crates/router/src/connector/worldline/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2895
Bug: [FEATURE]: Add ability to add connectors without any auth details ### Feature Description Ability to integrate a connector without any auth details. But it need not be used for routing until we get the auth details. ### Possible Implementation Create a new auth_type, which doesn't need any details and use the disabled field in the mca table to disable it in routing. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 6b9928734ce..efde4a04832 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -609,6 +609,9 @@ pub struct MerchantConnectorCreate { pub profile_id: Option<String>, pub pm_auth_config: Option<serde_json::Value>, + + #[schema(value_type = ConnectorStatus, example = "inactive")] + pub status: Option<api_enums::ConnectorStatus>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] @@ -714,6 +717,9 @@ pub struct MerchantConnectorResponse { pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + + #[schema(value_type = ConnectorStatus, example = "inactive")] + pub status: api_enums::ConnectorStatus, } /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." @@ -788,6 +794,9 @@ pub struct MerchantConnectorUpdate { pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, pub pm_auth_config: Option<serde_json::Value>, + + #[schema(value_type = ConnectorStatus, example = "inactive")] + pub status: Option<api_enums::ConnectorStatus>, } ///Details of FrmConfigs are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 8b1437fa892..cf3c398f8f4 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1857,3 +1857,25 @@ pub enum ApplePayFlow { Simplified, Manual, } + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + strum::Display, + strum::EnumString, + serde::Deserialize, + serde::Serialize, + ToSchema, + Default, +)] +#[router_derive::diesel_enum(storage_type = "pg_enum")] +#[strum(serialize_all = "snake_case")] +#[serde(rename_all = "snake_case")] +pub enum ConnectorStatus { + #[default] + Inactive, + Active, +} diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index ec021f0f51a..817fee63319 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -3,9 +3,10 @@ pub mod diesel_exports { pub use super::{ DbAttemptStatus as AttemptStatus, DbAuthenticationType as AuthenticationType, DbCaptureMethod as CaptureMethod, DbCaptureStatus as CaptureStatus, - DbConnectorType as ConnectorType, DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, - DbDisputeStage as DisputeStage, DbDisputeStatus as DisputeStatus, - DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType, + DbConnectorStatus as ConnectorStatus, DbConnectorType as ConnectorType, + DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDisputeStage as DisputeStage, + DbDisputeStatus as DisputeStatus, DbEventClass as EventClass, + DbEventObjectType as EventObjectType, DbEventType as EventType, DbFraudCheckStatus as FraudCheckStatus, DbFraudCheckType as FraudCheckType, DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbMandateType as MandateType, diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index a4faa45ce4b..e45ef002626 100644 --- a/crates/diesel_models/src/merchant_connector_account.rs +++ b/crates/diesel_models/src/merchant_connector_account.rs @@ -42,6 +42,7 @@ pub struct MerchantConnectorAccount { #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + pub status: storage_enums::ConnectorStatus, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -70,6 +71,7 @@ pub struct MerchantConnectorAccountNew { #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + pub status: storage_enums::ConnectorStatus, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] @@ -93,6 +95,7 @@ pub struct MerchantConnectorAccountUpdateInternal { #[diesel(deserialize_as = super::OptionalDieselArray<String>)] pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + pub status: Option<storage_enums::ConnectorStatus>, } impl MerchantConnectorAccountUpdateInternal { @@ -115,6 +118,7 @@ impl MerchantConnectorAccountUpdateInternal { frm_config: self.frm_config, modified_at: self.modified_at.unwrap_or(source.modified_at), pm_auth_config: self.pm_auth_config, + status: self.status.unwrap_or(source.status), ..source } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index e9db5714bed..190a123185e 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -492,6 +492,7 @@ diesel::table! { profile_id -> Nullable<Varchar>, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, pm_auth_config -> Nullable<Jsonb>, + status -> ConnectorStatus, } } diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs index ecea12203f8..6105dc85d7e 100644 --- a/crates/kgraph_utils/benches/evaluation.rs +++ b/crates/kgraph_utils/benches/evaluation.rs @@ -65,6 +65,7 @@ fn build_test_data<'a>(total_enabled: usize, total_pm_types: usize) -> graph::Kn profile_id: None, applepay_verified_domains: None, pm_auth_config: None, + status: api_enums::ConnectorStatus::Inactive, }; kgraph_utils::mca::make_mca_graph(vec![stripe_account]).expect("Failed graph construction") diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 34babd7a02b..deea51bd880 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -410,6 +410,7 @@ mod tests { profile_id: None, applepay_verified_domains: None, pm_auth_config: None, + status: api_enums::ConnectorStatus::Inactive, }; make_mca_graph(vec![stripe_account]).expect("Failed graph construction") diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index 54a7c461dbf..dfb49e8e677 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -334,6 +334,7 @@ impl TryFrom<&types::ConnectorAuthType> for SquareAuthType { | types::ConnectorAuthType::SignatureKey { .. } | types::ConnectorAuthType::MultiAuthKey { .. } | types::ConnectorAuthType::CurrencyAuthKey { .. } + | types::ConnectorAuthType::TemporaryAuth { .. } | types::ConnectorAuthType::NoKey { .. } => { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 39b4749535b..c921a9164cb 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -868,6 +868,15 @@ pub async fn create_payment_connector( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error updating the merchant account when creating payment connector")?; + let (connector_status, disabled) = validate_status_and_disabled( + req.status, + req.disabled, + auth, + // The validate_status_and_disabled function will use this value only + // when the status can be active. So we are passing this as fallback. + api_enums::ConnectorStatus::Active, + )?; + let merchant_connector_account = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_string(), connector_type: req.connector_type, @@ -886,7 +895,7 @@ pub async fn create_payment_connector( .attach_printable("Unable to encrypt connector account details")?, payment_methods_enabled, test_mode: req.test_mode, - disabled: req.disabled, + disabled, metadata: req.metadata, frm_configs, connector_label: Some(connector_label), @@ -911,6 +920,7 @@ pub async fn create_payment_connector( profile_id: Some(profile_id.clone()), applepay_verified_domains: None, pm_auth_config: req.pm_auth_config.clone(), + status: connector_status, }; let mut default_routing_config = @@ -1083,6 +1093,19 @@ pub async fn update_payment_connector( let frm_configs = get_frm_config_as_secret(req.frm_configs); + let auth: types::ConnectorAuthType = req + .connector_account_details + .clone() + .unwrap_or(mca.connector_account_details.clone().into_inner()) + .parse_value("ConnectorAuthType") + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_account_details".to_string(), + expected_format: "auth_type and api_key".to_string(), + })?; + + let (connector_status, disabled) = + validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?; + let payment_connector = storage::MerchantConnectorAccountUpdate::Update { merchant_id: None, connector_type: Some(req.connector_type), @@ -1098,7 +1121,7 @@ pub async fn update_payment_connector( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting data")?, test_mode: req.test_mode, - disabled: req.disabled, + disabled, payment_methods_enabled, metadata: req.metadata, frm_configs, @@ -1115,6 +1138,7 @@ pub async fn update_payment_connector( }, applepay_verified_domains: None, pm_auth_config: req.pm_auth_config, + status: Some(connector_status), }; let updated_mca = db @@ -1722,3 +1746,37 @@ pub async fn validate_dummy_connector_enabled( Ok(()) } } + +pub fn validate_status_and_disabled( + status: Option<api_enums::ConnectorStatus>, + disabled: Option<bool>, + auth: types::ConnectorAuthType, + current_status: api_enums::ConnectorStatus, +) -> RouterResult<(api_enums::ConnectorStatus, Option<bool>)> { + let connector_status = match (status, auth) { + (Some(common_enums::ConnectorStatus::Active), types::ConnectorAuthType::TemporaryAuth) => { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Connector status cannot be active when using TemporaryAuth".to_string(), + } + .into()); + } + (Some(status), _) => status, + (None, types::ConnectorAuthType::TemporaryAuth) => common_enums::ConnectorStatus::Inactive, + (None, _) => current_status, + }; + + let disabled = match (disabled, connector_status) { + (Some(true), common_enums::ConnectorStatus::Inactive) => { + return Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Connector cannot be enabled when connector_status is inactive or when using TemporaryAuth" + .to_string(), + } + .into()); + } + (Some(disabled), _) => Some(disabled), + (None, common_enums::ConnectorStatus::Inactive) => Some(true), + (None, _) => None, + }; + + Ok((connector_status, disabled)) +} diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs index 433430507fb..56960d3cb48 100644 --- a/crates/router/src/core/verification/utils.rs +++ b/crates/router/src/core/verification/utils.rs @@ -60,6 +60,7 @@ pub async fn check_existence_and_add_domain_to_db( applepay_verified_domains: Some(already_verified_domains.clone()), pm_auth_config: None, connector_label: None, + status: None, }; state .store diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index ecf52531f28..4fbb8f19ccf 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -643,6 +643,7 @@ impl MerchantConnectorAccountInterface for MockDb { profile_id: t.profile_id, applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, + status: t.status, }; accounts.push(account.clone()); account @@ -839,6 +840,7 @@ mod merchant_connector_account_cache_tests { profile_id: Some(profile_id.to_string()), applepay_verified_domains: None, pm_auth_config: None, + status: common_enums::ConnectorStatus::Inactive, }; db.insert_merchant_connector_account(mca.clone(), &merchant_key) diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 095e1f45f93..04ef90546cf 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -174,6 +174,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::AttemptStatus, api_models::enums::CaptureStatus, api_models::enums::ReconStatus, + api_models::enums::ConnectorStatus, api_models::admin::MerchantConnectorCreate, api_models::admin::MerchantConnectorUpdate, api_models::admin::PrimaryBusinessDetails, diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 7cf8f6b71fa..ceeb93f6976 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -900,6 +900,7 @@ pub struct ResponseRouterData<Flow, R, Request, Response> { #[derive(Default, Debug, Clone, serde::Deserialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { + TemporaryAuth, HeaderKey { api_key: Secret<String>, }, diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 58c2e018316..c84abbefc38 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -35,6 +35,7 @@ pub struct MerchantConnectorAccount { pub profile_id: Option<String>, pub applepay_verified_domains: Option<Vec<String>>, pub pm_auth_config: Option<serde_json::Value>, + pub status: enums::ConnectorStatus, } #[derive(Debug)] @@ -54,6 +55,7 @@ pub enum MerchantConnectorAccountUpdate { applepay_verified_domains: Option<Vec<String>>, pm_auth_config: Option<serde_json::Value>, connector_label: Option<String>, + status: Option<enums::ConnectorStatus>, }, } @@ -89,6 +91,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { profile_id: self.profile_id, applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, + status: self.status, }, ) } @@ -128,6 +131,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { profile_id: other.profile_id, applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, + status: other.status, }) } @@ -155,6 +159,7 @@ impl behaviour::Conversion for MerchantConnectorAccount { profile_id: self.profile_id, applepay_verified_domains: self.applepay_verified_domains, pm_auth_config: self.pm_auth_config, + status: self.status, }) } } @@ -177,6 +182,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte applepay_verified_domains, pm_auth_config, connector_label, + status, } => Self { merchant_id, connector_type, @@ -194,6 +200,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte applepay_verified_domains, pm_auth_config, connector_label, + status, }, } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 3ffba5aff50..2b7ea86cf51 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -852,6 +852,7 @@ impl TryFrom<domain::MerchantConnectorAccount> for api_models::admin::MerchantCo profile_id: item.profile_id, applepay_verified_domains: item.applepay_verified_domains, pm_auth_config: item.pm_auth_config, + status: item.status, }) } } diff --git a/migrations/2023-11-12-131143_connector-status-column/down.sql b/migrations/2023-11-12-131143_connector-status-column/down.sql new file mode 100644 index 00000000000..9463f4d7713 --- /dev/null +++ b/migrations/2023-11-12-131143_connector-status-column/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS status; +DROP TYPE IF EXISTS "ConnectorStatus"; diff --git a/migrations/2023-11-12-131143_connector-status-column/up.sql b/migrations/2023-11-12-131143_connector-status-column/up.sql new file mode 100644 index 00000000000..7a992d142d6 --- /dev/null +++ b/migrations/2023-11-12-131143_connector-status-column/up.sql @@ -0,0 +1,11 @@ +-- Your SQL goes here +CREATE TYPE "ConnectorStatus" AS ENUM ('active', 'inactive'); + +ALTER TABLE merchant_connector_account +ADD COLUMN status "ConnectorStatus"; + +UPDATE merchant_connector_account SET status='active'; + +ALTER TABLE merchant_connector_account +ALTER COLUMN status SET NOT NULL, +ALTER COLUMN status SET DEFAULT 'inactive'; diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index be66a1bff92..7d94f13dd12 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -4147,6 +4147,13 @@ } } }, + "ConnectorStatus": { + "type": "string", + "enum": [ + "inactive", + "active" + ] + }, "ConnectorType": { "type": "string", "enum": [ @@ -6871,7 +6878,8 @@ "description": "Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", "required": [ "connector_type", - "connector_name" + "connector_name", + "status" ], "properties": { "connector_type": { @@ -7002,6 +7010,9 @@ }, "pm_auth_config": { "nullable": true + }, + "status": { + "$ref": "#/components/schemas/ConnectorStatus" } } }, @@ -7087,7 +7098,8 @@ "required": [ "connector_type", "connector_name", - "merchant_connector_id" + "merchant_connector_id", + "status" ], "properties": { "connector_type": { @@ -7230,6 +7242,9 @@ }, "pm_auth_config": { "nullable": true + }, + "status": { + "$ref": "#/components/schemas/ConnectorStatus" } } }, @@ -7237,7 +7252,8 @@ "type": "object", "description": "Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", "required": [ - "connector_type" + "connector_type", + "status" ], "properties": { "connector_type": { @@ -7335,6 +7351,9 @@ }, "pm_auth_config": { "nullable": true + }, + "status": { + "$ref": "#/components/schemas/ConnectorStatus" } } },
2023-11-16T06:18:57Z
## Description <!-- Describe your changes in detail --> Add a new `auth_type` called `TemporaryAuth` which describes that auth details are not yet received. When using this `auth_type` the connector status will be `inactive` and mca will be disabled. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> To support connector integration without auth details. Closes #2895 #
94897d841e25d0be8debdfe1ec674f28848e2ad4
Postman. Payment Connector - Create and Payment Connector - Update now supports a new auth type called `TemporaryAuth` and a new field `status`. ``` curl --location 'http://localhost:8080/account/merchant_1700133263/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_name": "paypal", "connector_account_details": { "auth_type": "TemporaryAuth" }, "status": "inactive", "disabled": true }' ``` If `TemporaryAuth` is used in the request, the status field cannot be `active` and disabled cannot be `false`. This is applied for update mca as well. If a connector is inactive it cannot be enabled without changing the status to active. There are the following error messages that will be thrown if incorrect request is used. | auth_type | status | disabled | error_message | |---------------|----------|----------|-------------------------------------------------------------------------------------------| | TemoraryAuth | active | * | Connector status cannot be active when using TemporaryAuth | | TemporaryAuth | inactive | false | Connector cannot be enabled when connector_status is inactive or when using TemporaryAuth | | ValidAuth | inactive | false | Connector cannot be enabled when connector_status is inactive or when using TemporaryAuth | If all the fields are passed correctly you will a normal mca response.
[ "crates/api_models/src/admin.rs", "crates/common_enums/src/enums.rs", "crates/diesel_models/src/enums.rs", "crates/diesel_models/src/merchant_connector_account.rs", "crates/diesel_models/src/schema.rs", "crates/kgraph_utils/benches/evaluation.rs", "crates/kgraph_utils/src/mca.rs", "crates/router/src/c...
juspay/hyperswitch
juspay__hyperswitch-2860
Bug: [REFACTOR] : [Shift4] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 606da2129fb..ce68aad25c5 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -168,10 +168,9 @@ impl<T> TryFrom<&types::RouterData<T, types::PaymentsAuthorizeData, types::Payme | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()) } } @@ -184,13 +183,8 @@ impl TryFrom<&api_models::payments::WalletData> for Shift4PaymentMethod { match wallet_data { payments::WalletData::AliPayRedirect(_) | payments::WalletData::ApplePay(_) - | payments::WalletData::WeChatPayRedirect(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()) - } - payments::WalletData::AliPayQr(_) + | payments::WalletData::WeChatPayRedirect(_) + | payments::WalletData::AliPayQr(_) | payments::WalletData::AliPayHkRedirect(_) | payments::WalletData::MomoRedirect(_) | payments::WalletData::KakaoPayRedirect(_) @@ -212,10 +206,9 @@ impl TryFrom<&api_models::payments::WalletData> for Shift4PaymentMethod { | payments::WalletData::TouchNGoRedirect(_) | payments::WalletData::WeChatPayQr(_) | payments::WalletData::CashappQr(_) - | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + | payments::WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()), } } @@ -227,13 +220,8 @@ impl TryFrom<&api_models::payments::BankTransferData> for Shift4PaymentMethod { bank_transfer_data: &api_models::payments::BankTransferData, ) -> Result<Self, Self::Error> { match bank_transfer_data { - payments::BankTransferData::MultibancoBankTransfer { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()) - } - payments::BankTransferData::AchBankTransfer { .. } + payments::BankTransferData::MultibancoBankTransfer { .. } + | payments::BankTransferData::AchBankTransfer { .. } | payments::BankTransferData::SepaBankTransfer { .. } | payments::BankTransferData::BacsBankTransfer { .. } | payments::BankTransferData::PermataBankTransfer { .. } @@ -244,10 +232,9 @@ impl TryFrom<&api_models::payments::BankTransferData> for Shift4PaymentMethod { | payments::BankTransferData::DanamonVaBankTransfer { .. } | payments::BankTransferData::MandiriVaBankTransfer { .. } | payments::BankTransferData::Pix {} - | payments::BankTransferData::Pse {} => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + | payments::BankTransferData::Pse {} => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()), } } @@ -257,11 +244,8 @@ impl TryFrom<&api_models::payments::VoucherData> for Shift4PaymentMethod { type Error = Error; fn try_from(voucher_data: &api_models::payments::VoucherData) -> Result<Self, Self::Error> { match voucher_data { - payments::VoucherData::Boleto(_) => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()), - payments::VoucherData::Efecty + payments::VoucherData::Boleto(_) + | payments::VoucherData::Efecty | payments::VoucherData::PagoEfectivo | payments::VoucherData::RedCompra | payments::VoucherData::RedPagos @@ -273,10 +257,9 @@ impl TryFrom<&api_models::payments::VoucherData> for Shift4PaymentMethod { | payments::VoucherData::MiniStop(_) | payments::VoucherData::FamilyMart(_) | payments::VoucherData::Seicomart(_) - | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()), } } @@ -286,15 +269,12 @@ impl TryFrom<&api_models::payments::GiftCardData> for Shift4PaymentMethod { type Error = Error; fn try_from(gift_card_data: &api_models::payments::GiftCardData) -> Result<Self, Self::Error> { match gift_card_data { - payments::GiftCardData::Givex(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", + payments::GiftCardData::Givex(_) | payments::GiftCardData::PaySafeCard {} => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) + .into()) } - .into()), - payments::GiftCardData::PaySafeCard {} => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()), } } } @@ -401,10 +381,9 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme | Some(payments::PaymentMethodData::Reward) | Some(payments::PaymentMethodData::Upi(_)) | Some(api::PaymentMethodData::CardToken(_)) - | None => Err(errors::ConnectorError::NotSupported { - message: "Flow".to_string(), - connector: "Shift4", - } + | None => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()), } } @@ -421,13 +400,8 @@ impl TryFrom<&payments::BankRedirectData> for PaymentMethodType { payments::BankRedirectData::BancontactCard { .. } | payments::BankRedirectData::Blik { .. } | payments::BankRedirectData::Trustly { .. } - | payments::BankRedirectData::Przelewy24 { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Shift4"), - ) - .into()) - } - payments::BankRedirectData::Bizum {} + | payments::BankRedirectData::Przelewy24 { .. } + | payments::BankRedirectData::Bizum {} | payments::BankRedirectData::Interac { .. } | payments::BankRedirectData::OnlineBankingCzechRepublic { .. } | payments::BankRedirectData::OnlineBankingFinland { .. } @@ -436,10 +410,9 @@ impl TryFrom<&payments::BankRedirectData> for PaymentMethodType { | payments::BankRedirectData::OpenBankingUk { .. } | payments::BankRedirectData::OnlineBankingFpx { .. } | payments::BankRedirectData::OnlineBankingThailand { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Shift4", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Shift4"), + ) .into()) } }
2023-11-15T17:32:45Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context Resolves #2860 #
2e2dbe47156695beff6c0e4c800c0036fc426ed0
No test cases required. As In this PR only error message have been changed from Not Supported error message to NotImplemented error message.
[ "crates/router/src/connector/shift4/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2862
Bug: [REFACTOR] : [Stax] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs index bb37bf1fc9e..5aa0949a09c 100644 --- a/crates/router/src/connector/stax/transformers.rs +++ b/crates/router/src/connector/stax/transformers.rs @@ -63,10 +63,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme item: &StaxRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { if item.router_data.request.currency != enums::Currency::USD { - Err(errors::ConnectorError::NotSupported { - message: item.router_data.request.currency.to_string(), - connector: "Stax", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Stax"), + ))? } let total = item.amount; @@ -119,10 +118,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: "SELECTED_PAYMENT_METHOD".to_string(), - connector: "Stax", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Stax"), + ))?, } } } @@ -270,10 +268,9 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest { | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: "SELECTED_PAYMENT_METHOD".to_string(), - connector: "Stax", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Stax"), + ))?, } } }
2023-11-15T17:15:18Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context Resolves #2862 #
37ab392488350c22d1d1352edc90f46af25d40be
No test cases required. As In this PR only error message have been changed from Not Supported error message to NotImplemented error message.
[ "crates/router/src/connector/stax/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2864
Bug: [REFACTOR] : [Volt] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs index efed7c797c7..6f4c67dce8a 100644 --- a/crates/router/src/connector/volt/transformers.rs +++ b/crates/router/src/connector/volt/transformers.rs @@ -130,10 +130,9 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | api_models::payments::BankRedirectData::Trustly { .. } | api_models::payments::BankRedirectData::OnlineBankingFpx { .. } | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Volt", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Volt"), + ) .into()) } }, @@ -150,10 +149,9 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Volt", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Volt"), + ) .into()) } }
2023-11-15T17:01:47Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context Resolves #2864 #
37ab392488350c22d1d1352edc90f46af25d40be
No test cases required. As In this PR only error message have been changed from Not Supported error message to NotImplemented error message.
[ "crates/router/src/connector/volt/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2858
Bug: [REFACTOR] : [Paypal] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index baf8f48279d..88595585fe1 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -396,11 +396,9 @@ fn get_payment_source( | BankRedirectData::Trustly { .. } | BankRedirectData::OnlineBankingFpx { .. } | BankRedirectData::OnlineBankingThailand { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } - .into()) + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ))? } } } @@ -544,10 +542,9 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | api_models::payments::WalletData::WeChatPayQr(_) | api_models::payments::WalletData::CashappQr(_) | api_models::payments::WalletData::SwishQr(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ))? } }, api::PaymentMethodData::BankRedirect(ref bank_redirection_data) => { @@ -611,10 +608,9 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | api_models::payments::PaymentMethodData::Crypto(_) | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -629,10 +625,9 @@ impl TryFrom<&api_models::payments::CardRedirectData> for PaypalPaymentsRequest | api_models::payments::CardRedirectData::Benefit {} | api_models::payments::CardRedirectData::MomoAtm {} | api_models::payments::CardRedirectData::CardRedirect {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -651,10 +646,9 @@ impl TryFrom<&api_models::payments::PayLaterData> for PaypalPaymentsRequest { | api_models::payments::PayLaterData::WalleyRedirect {} | api_models::payments::PayLaterData::AlmaRedirect {} | api_models::payments::PayLaterData::AtomeRedirect {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -669,10 +663,9 @@ impl TryFrom<&api_models::payments::BankDebitData> for PaypalPaymentsRequest { | api_models::payments::BankDebitData::SepaBankDebit { .. } | api_models::payments::BankDebitData::BecsBankDebit { .. } | api_models::payments::BankDebitData::BacsBankDebit { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -696,10 +689,9 @@ impl TryFrom<&api_models::payments::BankTransferData> for PaypalPaymentsRequest | api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } | api_models::payments::BankTransferData::Pix {} | api_models::payments::BankTransferData::Pse {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -724,10 +716,9 @@ impl TryFrom<&api_models::payments::VoucherData> for PaypalPaymentsRequest { | api_models::payments::VoucherData::FamilyMart(_) | api_models::payments::VoucherData::Seicomart(_) | api_models::payments::VoucherData::PayEasy(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } } @@ -740,10 +731,9 @@ impl TryFrom<&api_models::payments::GiftCardData> for PaypalPaymentsRequest { match value { api_models::payments::GiftCardData::Givex(_) | api_models::payments::GiftCardData::PaySafeCard {} => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Paypal", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Paypal"), + ) .into()) } }
2023-11-15T16:31:13Z
## Description Refactored `NotSupported` Error calls to `NotImplemented` in the Paypal transformer. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> These changes fix the open issue #2858. #
94cd7b689758a71e13a3eaa655335e658d13afc8
Make any payment for Paypal connector for any PM which is not implemented, and see for the error message - it should be payment method not implemented
[ "crates/router/src/connector/paypal/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2861
Bug: [REFACTOR] : [Square] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs index e159b1d8ade..1e5501575ad 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/router/src/connector/square/transformers.rs @@ -4,7 +4,7 @@ use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{CardData, PaymentsAuthorizeRequestData, RouterData}, + connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData}, core::errors, types::{ self, api, @@ -17,19 +17,14 @@ impl TryFrom<(&types::TokenizationRouterData, BankDebitData)> for SquareTokenReq fn try_from( value: (&types::TokenizationRouterData, BankDebitData), ) -> Result<Self, Self::Error> { - let (item, bank_debit_data) = value; + let (_item, bank_debit_data) = value; match bank_debit_data { - BankDebitData::AchBankDebit { .. } => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - - BankDebitData::SepaBankDebit { .. } + BankDebitData::AchBankDebit { .. } + | BankDebitData::SepaBankDebit { .. } | BankDebitData::BecsBankDebit { .. } - | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -82,23 +77,18 @@ impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequ fn try_from( value: (&types::TokenizationRouterData, PayLaterData), ) -> Result<Self, Self::Error> { - let (item, pay_later_data) = value; + let (_item, pay_later_data) = value; match pay_later_data { - PayLaterData::AfterpayClearpayRedirect { .. } => Err( - errors::ConnectorError::NotImplemented("Payment Method".to_string()), - ) - .into_report(), - - PayLaterData::KlarnaRedirect { .. } + PayLaterData::AfterpayClearpayRedirect { .. } + | PayLaterData::KlarnaRedirect { .. } | PayLaterData::KlarnaSdk { .. } | PayLaterData::AffirmRedirect { .. } | PayLaterData::PayBrightRedirect { .. } | PayLaterData::WalleyRedirect { .. } | PayLaterData::AlmaRedirect { .. } - | PayLaterData::AtomeRedirect { .. } => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | PayLaterData::AtomeRedirect { .. } => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -106,18 +96,11 @@ impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(value: (&types::TokenizationRouterData, WalletData)) -> Result<Self, Self::Error> { - let (item, wallet_data) = value; + let (_item, wallet_data) = value; match wallet_data { - WalletData::ApplePay(_) => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - WalletData::GooglePay(_) => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - - WalletData::AliPayQr(_) + WalletData::ApplePay(_) + | WalletData::GooglePay(_) + | WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) | WalletData::AliPayHkRedirect(_) | WalletData::MomoRedirect(_) @@ -140,10 +123,9 @@ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenReques | WalletData::WeChatPayRedirect(_) | WalletData::WeChatPayQr(_) | WalletData::CashappQr(_) - | WalletData::SwishQr(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | WalletData::SwishQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -180,11 +162,8 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { api::PaymentMethodData::PayLater(pay_later_data) => { Self::try_from((item, pay_later_data)) } - api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - api::PaymentMethodData::BankRedirect(_) + api::PaymentMethodData::GiftCard(_) + | api::PaymentMethodData::BankRedirect(_) | api::PaymentMethodData::BankTransfer(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Crypto(_) @@ -192,10 +171,9 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -297,11 +275,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { api::PaymentMethodData::BankDebit(_) | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::PayLater(_) - | api::PaymentMethodData::Wallet(_) => Err(errors::ConnectorError::NotImplemented( - "Payment Method".to_string(), - )) - .into_report(), - api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::Wallet(_) + | api::PaymentMethodData::BankRedirect(_) | api::PaymentMethodData::BankTransfer(_) | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Crypto(_) @@ -309,10 +284,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { | api::PaymentMethodData::Reward | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Square", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } }
2023-11-15T11:06:58Z
## Description Consistent error messages for not implemented payment method. ## Motivation and Context Resolves #2861 #
0666d814af93045ff23c85d8fd796da08cd5749b
payment connector create ``` { "connector_type": "fiz_operations", "connector_name": "volt", "connector_account_details": { "auth_type": "MultiAuthKey", "api_key": "{{connector_api_key}}", "api_secret": "{{connector_api_secret}}", "key1": "{{connector_key1}}", "key2": "{{connector_key2}}" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "open_banking_uk", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": false, "installment_payment_enabled": false // "accepted_currencies": { // "type": "enable_only", // "list": [ // "EUR" // ] // }, // "accepted_countries": { // "type": "enable_only", // "list": [ // "DE" // ] // } } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "dce1d767-7c28-429c-b0fe-9e0b9e91f962" }, "business_country": "US", "business_label": "food" } ``` create a payment which is not implemented Payment create ``` { "amount": 6540, "currency": "BRL", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "bank_transfer", "payment_method_type": "pix", "payment_method_data": { "bank_transfer": { "pix": {} } }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "PiX" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } } ``` Make any payment for Square for any PM which is not implemented, and see for the error message - it should be payment method not implemented
[ "crates/router/src/connector/square/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-1973
Bug: [FEATURE] Use empty enums instead of unit structs for PII masking strategies ### Feature Description Currently, we make use of unit structs that implement the `masking::Strategy<T>` trait to represent PII masking strategies. We would like to replace these with empty enums instead (So `struct MyStrategy;` becomes `enum MyStrategy {}`). The difference between the two is that you can still construct a value out of a unit struct, but you can never construct a value out of an empty enum (since it has no variants to construct). However, you can still use empty enums as type parameters to generic constructs like the `masking::Secret<Data, Strategy>` type. The argument against this is that we wouldn't be able to construct a `dyn masking::Strategy<T>`, but ideally, owing to the current implementation of PII masking in Hyperswitch, we should never have the need to obtain a `dyn masking::Strategy<T>` trait object. ### Possible Implementation For all unit structs that implement `masking::Strategy<T>`, convert them to unit enums. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index db6957057ec..d083a420a1e 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -72,7 +72,7 @@ impl<'de> Deserialize<'de> for CardNumber { } } -pub struct CardNumberStrategy; +pub enum CardNumberStrategy {} impl<T> Strategy<T> for CardNumberStrategy where diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index c246d204226..39793de5c2b 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -27,7 +27,7 @@ pub type SecretSerdeValue = Secret<serde_json::Value>; /// Strategy for masking a PhoneNumber #[derive(Debug)] -pub struct PhoneNumberStrategy; +pub enum PhoneNumberStrategy {} /// Phone Number #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -144,7 +144,7 @@ where /// Strategy for Encryption #[derive(Debug)] -pub struct EncryptionStratergy; +pub enum EncryptionStratergy {} impl<T> Strategy<T> for EncryptionStratergy where @@ -157,7 +157,7 @@ where /// Client secret #[derive(Debug)] -pub struct ClientSecret; +pub enum ClientSecret {} impl<T> Strategy<T> for ClientSecret where @@ -189,7 +189,7 @@ where /// Strategy for masking Email #[derive(Debug)] -pub struct EmailStrategy; +pub enum EmailStrategy {} impl<T> Strategy<T> for EmailStrategy where @@ -305,7 +305,7 @@ impl FromStr for Email { /// IP address #[derive(Debug)] -pub struct IpAddress; +pub enum IpAddress {} impl<T> Strategy<T> for IpAddress where @@ -332,7 +332,7 @@ where /// Strategy for masking UPI VPA's #[derive(Debug)] -pub struct UpiVpaMaskingStrategy; +pub enum UpiVpaMaskingStrategy {} impl<T> Strategy<T> for UpiVpaMaskingStrategy where diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index 96411d4632b..b2e9124688c 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -12,8 +12,8 @@ use crate::{strategy::Strategy, PeekInterface}; /// To get access to value use method `expose()` of trait [`crate::ExposeInterface`]. /// /// ## Masking -/// Use the [`crate::strategy::Strategy`] trait to implement a masking strategy on a unit struct -/// and pass the unit struct as a second generic parameter to [`Secret`] while defining it. +/// Use the [`crate::strategy::Strategy`] trait to implement a masking strategy on a zero-variant +/// enum and pass this enum as a second generic parameter to [`Secret`] while defining it. /// [`Secret`] will take care of applying the masking strategy on the inner secret when being /// displayed. /// @@ -24,7 +24,7 @@ use crate::{strategy::Strategy, PeekInterface}; /// use masking::Secret; /// use std::fmt; /// -/// struct MyStrategy; +/// enum MyStrategy {} /// /// impl<T> Strategy<T> for MyStrategy /// where diff --git a/crates/masking/src/strategy.rs b/crates/masking/src/strategy.rs index f744ee1f4b5..8b4d9b0ec34 100644 --- a/crates/masking/src/strategy.rs +++ b/crates/masking/src/strategy.rs @@ -7,7 +7,7 @@ pub trait Strategy<T> { } /// Debug with type -pub struct WithType; +pub enum WithType {} impl<T> Strategy<T> for WithType { fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -18,7 +18,7 @@ impl<T> Strategy<T> for WithType { } /// Debug without type -pub struct WithoutType; +pub enum WithoutType {} impl<T> Strategy<T> for WithoutType { fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2023-11-15T09:48:54Z
as per #1973 ## Description Use empty enums as strategy type parameter, instead of unit structs, to prevent instantiation. ## Motivation and Context #1973 #
54d6b1083fab5d2b0c7637c150524460a16a3fec
`cargo clippy --all-features` Assuming existing tests should catch side effects if any.
[ "crates/cards/src/validate.rs", "crates/common_utils/src/pii.rs", "crates/masking/src/secret.rs", "crates/masking/src/strategy.rs" ]
juspay/hyperswitch
juspay__hyperswitch-3003
Bug: [BUG]: [Dlocal] connector transaction id fix ### Bug Description The Dlocal connector Transaction ID wasn't correctly populated, causing failures in subsequent operations like capture, refund, and 3DS redirection. ### Expected Behavior Transaction id should be mapped to `item.response.id` in connector response and all subsequent actions should be functional . ### Actual Behavior The Dlocal connector Transaction ID wasn't correctly populated, causing failures in subsequent operations like capture, refund, and 3DS redirection. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' Try making 3ds payment via Dlocal ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs index 668a335cce8..66cf413e991 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/router/src/connector/dlocal/transformers.rs @@ -302,7 +302,7 @@ pub struct DlocalPaymentsResponse { status: DlocalPaymentStatus, id: String, three_dsecure: Option<ThreeDSecureResData>, - order_id: String, + order_id: Option<String>, } impl<F, T> @@ -322,12 +322,12 @@ impl<F, T> }); let response = types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id.clone()), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: Some(item.response.order_id.clone()), + connector_response_reference_id: item.response.order_id.clone(), }; Ok(Self { status: enums::AttemptStatus::from(item.response.status), @@ -341,7 +341,7 @@ impl<F, T> pub struct DlocalPaymentsSyncResponse { status: DlocalPaymentStatus, id: String, - order_id: String, + order_id: Option<String>, } impl<F, T> @@ -361,14 +361,12 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.order_id.clone(), - ), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: Some(item.response.order_id.clone()), + connector_response_reference_id: item.response.order_id.clone(), }), ..item.data }) @@ -379,7 +377,7 @@ impl<F, T> pub struct DlocalPaymentsCaptureResponse { status: DlocalPaymentStatus, id: String, - order_id: String, + order_id: Option<String>, } impl<F, T> @@ -399,14 +397,12 @@ impl<F, T> Ok(Self { status: enums::AttemptStatus::from(item.response.status), response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.order_id.clone(), - ), + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, - connector_response_reference_id: Some(item.response.order_id.clone()), + connector_response_reference_id: item.response.order_id.clone(), }), ..item.data })
2023-11-14T19:49:53Z
## Description - Fix: Dlocal Connector Transaction ID Population Issue ## Motivation and Context - Why is this change required? What problem does it solve? A.) The Dlocal connector Transaction ID wasn't correctly populated, causing failures in subsequent operations like capture, refund, and 3DS redirection. This fix ensures the proper population of the Transaction ID, resolving the associated failures. <!-- If it fixes an open issue, please link to the issue here. No If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
496245d990e123b626089e70c848856ace295fb5
Executed the following test scenario using the Postman collection: - Initiated a 3DS-authorized transaction - Successfully completed the authorization process - Captured the payment" <img width="1512" alt="Dlocal capture" src="https://github.com/juspay/hyperswitch/assets/50401745/711a23ce-05d3-43a6-828b-db2d7ca77522"> <img width="1512" alt="dlocal after redirection" src="https://github.com/juspay/hyperswitch/assets/50401745/b801aed1-7768-47b0-ae4a-44ef1206621c"> <img width="1512" alt="Dlocal 3ds" src="https://github.com/juspay/hyperswitch/assets/50401745/4ffc3397-3f79-4d2a-a275-35134c469030">
[ "crates/router/src/connector/dlocal/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2855
Bug: [REFACTOR] : [Nuvei] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index c23114e2a96..3c9686c4e22 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -623,11 +623,9 @@ impl TryFrom<api_models::enums::BankNames> for NuveiBIC { | api_models::enums::BankNames::TsbBank | api_models::enums::BankNames::TescoBank | api_models::enums::BankNames::UlsterBank => { - Err(errors::ConnectorError::NotSupported { - message: bank.to_string(), - connector: "Nuvei", - } - .into()) + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Nuvei"), + ))? } } } @@ -693,10 +691,9 @@ impl<F> bank_name.map(NuveiBIC::try_from).transpose()?, ) } - _ => Err(errors::ConnectorError::NotSupported { - message: "Bank Redirect".to_string(), - connector: "Nuvei", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Nuvei"), + ))?, }; Ok(Self { payment_option: PaymentOption {
2023-11-13T08:52:39Z
## Description <!-- Describe your changes in detail --> - Fix issue: #2855 - Changes to be made: update the error message - File changed: **```transformers.rs```** (crates/router/src/connector/nuvei/transformers.rs) ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> # ## Test Cases Check for BankRedirect which is not implemented, here we can check for Przelewy24 and we should get `notImplemented` error message. ``` "payment_method": "bank_redirect", "payment_method_type": "przelewy_24", "payment_method_data": { "bank_redirect": { "eps": { "billing_details": { "email": "jane@jones.com" } } } }, ```
f88eee7362be2cc3e8e8dc2bb7bfd263892ff01e
[ "crates/router/src/connector/nuvei/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2842
Bug: [REFACTOR] : [Multisafepay] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 1780b77379c..fb62643d667 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -262,10 +262,9 @@ impl TryFrom<utils::CardIssuer> for Gateway { utils::CardIssuer::Visa => Ok(Self::Visa), utils::CardIssuer::DinersClub | utils::CardIssuer::JCB - | utils::CardIssuer::CarteBlanche => Err(errors::ConnectorError::NotSupported { - message: issuer.to_string(), - connector: "Multisafe pay", - } + | utils::CardIssuer::CarteBlanche => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Multisafe pay"), + ) .into()), } }
2023-11-11T20:15:57Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
de8e31b70d9b3c11e268cd1deffa71918dc4270d
[ "crates/router/src/connector/multisafepay/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2841
Bug: [REFACTOR] : [Helcim] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs index dc38b2eeb25..1a5a8baa7ee 100644 --- a/crates/router/src/connector/helcim/transformers.rs +++ b/crates/router/src/connector/helcim/transformers.rs @@ -143,10 +143,9 @@ impl TryFrom<&types::SetupMandateRouterData> for HelcimVerifyRequest { | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.request.payment_method_data), - connector: "Helcim", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Helcim"), + ))? } } } @@ -225,10 +224,9 @@ impl TryFrom<&HelcimRouterData<&types::PaymentsAuthorizeRouterData>> for HelcimP | api_models::payments::PaymentMethodData::Upi(_) | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.router_data.request.payment_method_data), - connector: "Helcim", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Helcim"), + ))?, } } }
2023-11-11T20:11:13Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
bc79d522c30aa036378cf1e01354c422585cc226
[ "crates/router/src/connector/helcim/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2844
Bug: [REFACTOR] : [Noon] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index ee06cd064be..8bb3a96a3ca 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -275,10 +275,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { | api_models::payments::WalletData::WeChatPayQr(_) | api_models::payments::WalletData::CashappQr(_) | api_models::payments::WalletData::SwishQr(_) => { - Err(errors::ConnectorError::NotSupported { - message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Noon", - }) + Err(errors::ConnectorError::NotImplemented( + conn_utils::get_unimplemented_payment_method_error_message("Noon"), + )) } }, api::PaymentMethodData::CardRedirect(_) @@ -293,10 +292,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { | api::PaymentMethodData::Voucher(_) | api::PaymentMethodData::GiftCard(_) | api::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: conn_utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Noon", - }) + Err(errors::ConnectorError::NotImplemented( + conn_utils::get_unimplemented_payment_method_error_message("Noon"), + )) } }?, Some(item.request.currency),
2023-11-11T20:02:31Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
1828ea6187c46d9c18dc8a0b5224387403b998e2
Make any payment for Noon connector for any PM which is not implemented, and see for the error message - it should be payment method not implemented
[ "crates/router/src/connector/noon/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2843
Bug: [REFACTOR] : [NMI] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index fcf35bfbe37..5b486aae600 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -494,10 +494,9 @@ impl TryFrom<&api_models::payments::PaymentMethodData> for PaymentMethod { | api_models::payments::WalletData::WeChatPayQr(_) | api_models::payments::WalletData::CashappQr(_) | api_models::payments::WalletData::SwishQr(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "nmi", - }) + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("nmi"), + )) .into_report() } }, @@ -512,10 +511,9 @@ impl TryFrom<&api_models::payments::PaymentMethodData> for PaymentMethod { | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) | api::PaymentMethodData::GiftCard(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "nmi", - }) + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("nmi"), + )) .into_report(), } }
2023-11-11T20:00:09Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
db3d53ff1d8b42d107fafe7a6efe7ec9f155d5a0
Make any payment for NMI for any PM which is not implemented, and see for the error message - it should be payment method not implemented
[ "crates/router/src/connector/nmi/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2840
Bug: [REFACTOR] : [Forte] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs index 4bb354f6cda..56555a0d97e 100644 --- a/crates/router/src/connector/forte/transformers.rs +++ b/crates/router/src/connector/forte/transformers.rs @@ -54,10 +54,9 @@ impl TryFrom<utils::CardIssuer> for ForteCardType { utils::CardIssuer::Visa => Ok(Self::Visa), utils::CardIssuer::DinersClub => Ok(Self::DinersClub), utils::CardIssuer::JCB => Ok(Self::Jcb), - _ => Err(errors::ConnectorError::NotSupported { - message: issuer.to_string(), - connector: "Forte", - } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Forte"), + ) .into()), } } @@ -67,10 +66,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { if item.request.currency != enums::Currency::USD { - Err(errors::ConnectorError::NotSupported { - message: item.request.currency.to_string(), - connector: "Forte", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Forte"), + ))? } match item.request.payment_method_data { api_models::payments::PaymentMethodData::Card(ref ccard) => { @@ -114,10 +112,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest { | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Forte", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Forte"), + ))? } } }
2023-11-11T19:54:50Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
bc79d522c30aa036378cf1e01354c422585cc226
[ "crates/router/src/connector/forte/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2839
Bug: [REFACTOR] : [CryptoPay] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs index 3af604c786b..4102945b201 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/router/src/connector/cryptopay/transformers.rs @@ -82,10 +82,9 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> | api_models::payments::PaymentMethodData::Voucher(_) | api_models::payments::PaymentMethodData::GiftCard(_) | api_models::payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "CryptoPay", - }) + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("CryptoPay"), + )) } }?; Ok(cryptopay_request)
2023-11-11T19:51:04Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
bc79d522c30aa036378cf1e01354c422585cc226
[ "crates/router/src/connector/cryptopay/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2838
Bug: [REFACTOR] : [Adyen] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 1eede78503b..aa5cd2ec695 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -752,10 +752,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingCzechRepublicBanks { api::enums::BankNames::KomercniBanka => Ok(Self::KB), api::enums::BankNames::CeskaSporitelna => Ok(Self::CS), api::enums::BankNames::PlatnoscOnlineKartaPlatnicza => Ok(Self::C), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -832,10 +831,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingPolandBanks { api_models::enums::BankNames::ToyotaBank => Ok(Self::ToyotaBank), api_models::enums::BankNames::VeloBank => Ok(Self::VeloBank), api_models::enums::BankNames::ETransferPocztowy24 => Ok(Self::ETransferPocztowy24), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -884,10 +882,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingSlovakiaBanks { api::enums::BankNames::SporoPay => Ok(Self::Sporo), api::enums::BankNames::TatraPay => Ok(Self::Tatra), api::enums::BankNames::Viamo => Ok(Self::Viamo), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -914,10 +911,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingFpxIssuer { api::enums::BankNames::RhbBank => Ok(Self::FpxRhb), api::enums::BankNames::StandardCharteredBank => Ok(Self::FpxScb), api::enums::BankNames::UobBank => Ok(Self::FpxUob), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -931,10 +927,9 @@ impl TryFrom<&api_enums::BankNames> for OnlineBankingThailandIssuer { api::enums::BankNames::KrungThaiBank => Ok(Self::Krungthaibank), api::enums::BankNames::TheSiamCommercialBank => Ok(Self::Siamcommercialbank), api::enums::BankNames::KasikornBank => Ok(Self::Kbank), - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -1087,10 +1082,9 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer { | enums::BankNames::Yoursafe | enums::BankNames::N26 | enums::BankNames::NationaleNederlanden - | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + | enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, } } } @@ -1484,10 +1478,9 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> { api_models::enums::BankNames::VolkskreditbankAg => { Self("4a0a975b-0594-4b40-9068-39f77b3a91f9") } - _ => Err(errors::ConnectorError::NotSupported { - message: String::from("BankRedirect"), - connector: "Adyen", - })?, + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))?, }) } } @@ -1591,10 +1584,9 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> | payments::PaymentMethodData::Reward | payments::PaymentMethodData::Upi(_) | payments::PaymentMethodData::CardToken(_) => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - })? + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ))? } }, } @@ -1893,10 +1885,9 @@ impl<'a> TryFrom<&api_models::payments::BankDebitData> for AdyenPaymentMethod<'a }, ))), payments::BankDebitData::BecsBankDebit { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) .into()) } } @@ -1944,10 +1935,9 @@ impl<'a> TryFrom<&api_models::payments::VoucherData> for AdyenPaymentMethod<'a> payments::VoucherData::Efecty | payments::VoucherData::PagoEfectivo | payments::VoucherData::RedCompra - | payments::VoucherData::RedPagos => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - } + | payments::VoucherData::RedPagos => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) .into()), } } @@ -2131,10 +2121,9 @@ impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> { | payments::WalletData::GooglePayThirdPartySdk(_) | payments::WalletData::PaypalSdk(_) | payments::WalletData::WeChatPayQr(_) - | payments::WalletData::CashappQr(_) => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - } + | payments::WalletData::CashappQr(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) .into()), } } @@ -2264,11 +2253,12 @@ impl<'a> check_required_field(billing_address, "billing")?; Ok(AdyenPaymentMethod::Atome) } - payments::PayLaterData::KlarnaSdk { .. } => Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", + payments::PayLaterData::KlarnaSdk { .. } => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) + .into()) } - .into()), } } } @@ -2428,10 +2418,9 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)> } payments::BankRedirectData::Interac { .. } | payments::BankRedirectData::Przelewy24 { .. } => { - Err(errors::ConnectorError::NotSupported { - message: utils::SELECTED_PAYMENT_METHOD.to_string(), - connector: "Adyen", - } + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyen"), + ) .into()) } }
2023-11-11T19:43:05Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
708cce926125a29b406db48cf0ebd35b217927d4
Test a Payment Method which is not implemented It should give Not implemented error This is an Crypto payment request. ``` { "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_method_data": { "crypto": {} }, "routing": { "type": "single", "data": "adyen" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Swangi" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Swangi" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "profile_id": "pro_16j8JOCurimvr2XXG9EE" } ``` This is a Payment Method which is not implemented for adyen
[ "crates/router/src/connector/adyen/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2836
Bug: [REFACTOR] : [ACI] Error Message For Connector Implementation ### :memo: Feature Description - In terms of errors, we are currently throwing a 'not supported' message, which shouldn't be the case as we are yet to decide on the implementation. ### :hammer: Possible Implementation - In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant. - By doing so, we will throw same error message for all the Connector Implementation - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2831 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 9cfb657bdca..8eea6dbb4d5 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -410,10 +410,9 @@ impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPayment | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) - | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.router_data.payment_method), - connector: "Aci", - })?, + | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Aci"), + ))?, } } }
2023-11-11T07:35:43Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context #
bc79d522c30aa036378cf1e01354c422585cc226
Manual checking
[ "crates/router/src/connector/aci/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2833
Bug: [FEATURE] Add support for profile-specific default routing fallback ### Feature Description Currently every merchant has a default fallback which is a list of all of their configured connectors. We now want to make this profile-specific, i.e. each profile will have an associated default fallback that is a list of all the connectors associated with that profile. This issue also entails development of Read/Write APIs for profile specific default fallbacks, and integration with the payments core. Further on , we can also later on add the `mca_id` as many connectors with the same name can be there under a single `profile_id` ### Possible Implementation In interest of backwards compatibility, create two separate default fallback APIs for profiles (Read & Write). Additionally, implement profile-specific fallback usage in payments core routing with a feature flag. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? No, but I'm happy to collaborate on a PR with someone else
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs index 5eca01acc6f..a09735bc572 100644 --- a/crates/api_models/src/events/routing.rs +++ b/crates/api_models/src/events/routing.rs @@ -1,8 +1,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::routing::{ - LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, RoutingAlgorithmId, - RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, + LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig, + RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, + RoutingPayloadWrapper, }; #[cfg(feature = "business_profile_routing")] use crate::routing::{RoutingRetrieveLinkQuery, RoutingRetrieveQuery}; @@ -37,6 +38,17 @@ impl ApiEventMetric for LinkedRoutingConfigRetrieveResponse { } } +impl ApiEventMetric for RoutingPayloadWrapper { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} +impl ApiEventMetric for ProfileDefaultRoutingConfig { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + #[cfg(feature = "business_profile_routing")] impl ApiEventMetric for RoutingRetrieveQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 425ca364191..363df5389a7 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -40,6 +40,12 @@ pub struct RoutingConfigRequest { pub profile_id: Option<String>, } +#[derive(Debug, serde::Serialize)] +pub struct ProfileDefaultRoutingConfig { + pub profile_id: String, + pub connectors: Vec<RoutableConnectorChoice>, +} + #[cfg(feature = "business_profile_routing")] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveQuery { @@ -389,6 +395,13 @@ pub enum RoutingAlgorithmKind { Advanced, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] + +pub struct RoutingPayloadWrapper { + pub updated_config: Vec<RoutableConnectorChoice>, + pub profile_id: String, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde( tag = "type", diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index d765a5b5c5e..8f6906e0685 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -9,13 +9,13 @@ readme = "README.md" license.workspace = true [features] -default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts"] +default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "profile_specific_fallback_routing"] s3 = ["dep:aws-sdk-s3", "dep:aws-config"] kms = ["external_services/kms", "dep:aws-config"] email = ["external_services/email", "dep:aws-config"] basilisk = ["kms"] stripe = ["dep:serde_qs"] -release = ["kms", "stripe", "basilisk", "s3", "email", "business_profile_routing", "accounts_cache", "kv_store", "olap"] +release = ["kms", "stripe", "basilisk", "s3", "email", "business_profile_routing", "accounts_cache", "kv_store", "profile_specific_fallback_routing"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap"] oltp = ["data_models/oltp", "storage_impl/oltp"] kv_store = ["scheduler/kv_store"] @@ -24,6 +24,7 @@ openapi = ["olap", "oltp", "payouts"] vergen = ["router_env/vergen"] backwards_compatibility = ["api_models/backwards_compatibility", "euclid/backwards_compatibility", "kgraph_utils/backwards_compatibility"] business_profile_routing=["api_models/business_profile_routing"] +profile_specific_fallback_routing = [] dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "kgraph_utils/dummy_connector"] connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connector_choice_mca_id", "kgraph_utils/connector_choice_mca_id"] external_access_dc = ["dummy_connector"] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index e1e5ea744e2..5ccd9e96486 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -916,13 +916,16 @@ pub async fn create_payment_connector( let mut default_routing_config = routing_helpers::get_merchant_default_config(&*state.store, merchant_id).await?; + let mut default_routing_config_for_profile = + routing_helpers::get_merchant_default_config(&*state.clone().store, &profile_id).await?; + let mca = state .store .insert_merchant_connector_account(merchant_connector_account, &key_store) .await .to_duplicate_response( errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { - profile_id, + profile_id: profile_id.clone(), connector_name: req.connector_name.to_string(), }, )?; @@ -939,7 +942,7 @@ pub async fn create_payment_connector( }; if !default_routing_config.contains(&choice) { - default_routing_config.push(choice); + default_routing_config.push(choice.clone()); routing_helpers::update_merchant_default_config( &*state.store, merchant_id, @@ -947,6 +950,15 @@ pub async fn create_payment_connector( ) .await?; } + if !default_routing_config_for_profile.contains(&choice.clone()) { + default_routing_config_for_profile.push(choice); + routing_helpers::update_merchant_default_config( + &*state.store, + &profile_id.clone(), + default_routing_config_for_profile, + ) + .await?; + } } metrics::MCA_CREATE.add( diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 4134ddf65ea..3b89d4e38e4 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -71,7 +71,10 @@ pub struct SessionRoutingPmTypeInput<'a> { routing_algorithm: &'a MerchantAccountRoutingAlgorithm, backend_input: dsl_inputs::BackendInput, allowed_connectors: FxHashMap<String, api::GetToken>, - #[cfg(feature = "business_profile_routing")] + #[cfg(any( + feature = "business_profile_routing", + feature = "profile_specific_fallback_routing" + ))] profile_id: Option<String>, } static ROUTING_CACHE: StaticCache<CachedAlgorithm> = StaticCache::new(); @@ -207,10 +210,22 @@ pub async fn perform_static_routing_v1<F: Clone>( let algorithm_id = if let Some(id) = algorithm_ref.algorithm_id { id } else { - let fallback_config = - routing_helpers::get_merchant_default_config(&*state.clone().store, merchant_id) - .await - .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; + let fallback_config = routing_helpers::get_merchant_default_config( + &*state.clone().store, + #[cfg(not(feature = "profile_specific_fallback_routing"))] + merchant_id, + #[cfg(feature = "profile_specific_fallback_routing")] + { + payment_data + .payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::RoutingError::ProfileIdMissing)? + }, + ) + .await + .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; return Ok(fallback_config); }; @@ -616,10 +631,22 @@ pub async fn perform_fallback_routing<F: Clone>( eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>, #[cfg(feature = "business_profile_routing")] profile_id: Option<String>, ) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> { - let fallback_config = - routing_helpers::get_merchant_default_config(&*state.store, &key_store.merchant_id) - .await - .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; + let fallback_config = routing_helpers::get_merchant_default_config( + &*state.store, + #[cfg(not(feature = "profile_specific_fallback_routing"))] + &key_store.merchant_id, + #[cfg(feature = "profile_specific_fallback_routing")] + { + payment_data + .payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::RoutingError::ProfileIdMissing)? + }, + ) + .await + .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; let backend_input = make_dsl_input(payment_data)?; perform_kgraph_filtering( @@ -819,8 +846,11 @@ pub async fn perform_session_flow_routing( routing_algorithm: &routing_algorithm, backend_input: backend_input.clone(), allowed_connectors, - #[cfg(feature = "business_profile_routing")] - profile_id: session_input.payment_intent.clone().profile_id, + #[cfg(any( + feature = "business_profile_routing", + feature = "profile_specific_fallback_routing" + ))] + profile_id: session_input.payment_intent.profile_id.clone(), }; let maybe_choice = perform_session_routing_for_pm_type(session_pm_input).await?; @@ -880,7 +910,16 @@ async fn perform_session_routing_for_pm_type( } else { routing_helpers::get_merchant_default_config( &*session_pm_input.state.clone().store, + #[cfg(not(feature = "profile_specific_fallback_routing"))] merchant_id, + #[cfg(feature = "profile_specific_fallback_routing")] + { + session_pm_input + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::RoutingError::ProfileIdMissing)? + }, ) .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)? @@ -903,7 +942,16 @@ async fn perform_session_routing_for_pm_type( if final_selection.is_empty() { let fallback = routing_helpers::get_merchant_default_config( &*session_pm_input.state.clone().store, + #[cfg(not(feature = "profile_specific_fallback_routing"))] merchant_id, + #[cfg(feature = "profile_specific_fallback_routing")] + { + session_pm_input + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::RoutingError::ProfileIdMissing)? + }, ) .await .change_context(errors::RoutingError::FallbackConfigFetchFailed)?; diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 723611ed500..4171c338563 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -13,13 +13,14 @@ use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::{IntoReport, ResultExt}; use rustc_hash::FxHashSet; -#[cfg(feature = "business_profile_routing")] -use crate::core::utils::validate_and_get_business_profile; #[cfg(feature = "business_profile_routing")] use crate::types::transformers::{ForeignInto, ForeignTryInto}; use crate::{ consts, - core::errors::{RouterResponse, StorageErrorExt}, + core::{ + errors::{RouterResponse, StorageErrorExt}, + utils as core_utils, + }, routes::AppState, types::domain, utils::{self, OptionExt, ValueExt}, @@ -111,8 +112,12 @@ pub async fn create_routing_config( }) .attach_printable("Profile_id not provided")?; - validate_and_get_business_profile(db, Some(&profile_id), &merchant_account.merchant_id) - .await?; + core_utils::validate_and_get_business_profile( + db, + Some(&profile_id), + &merchant_account.merchant_id, + ) + .await?; helpers::validate_connectors_in_routing_config( db, @@ -229,7 +234,7 @@ pub async fn link_routing_config( .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?; - let business_profile = validate_and_get_business_profile( + let business_profile = core_utils::validate_and_get_business_profile( db, Some(&routing_algorithm.profile_id), &merchant_account.merchant_id, @@ -332,7 +337,7 @@ pub async fn retrieve_routing_config( .await .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; - validate_and_get_business_profile( + core_utils::validate_and_get_business_profile( db, Some(&routing_algorithm.profile_id), &merchant_account.merchant_id, @@ -401,9 +406,12 @@ pub async fn unlink_routing_config( field_name: "profile_id", }) .attach_printable("Profile_id not provided")?; - let business_profile = - validate_and_get_business_profile(db, Some(&profile_id), &merchant_account.merchant_id) - .await?; + let business_profile = core_utils::validate_and_get_business_profile( + db, + Some(&profile_id), + &merchant_account.merchant_id, + ) + .await?; match business_profile { Some(business_profile) => { let routing_algo_ref: routing_types::RoutingAlgorithmRef = business_profile @@ -622,13 +630,15 @@ pub async fn retrieve_linked_routing_config( #[cfg(feature = "business_profile_routing")] { let business_profiles = if let Some(profile_id) = query_params.profile_id { - validate_and_get_business_profile(db, Some(&profile_id), &merchant_account.merchant_id) - .await? - .map(|profile| vec![profile]) - .get_required_value("BusinessProfile") - .change_context(errors::ApiErrorResponse::BusinessProfileNotFound { - id: profile_id, - })? + core_utils::validate_and_get_business_profile( + db, + Some(&profile_id), + &merchant_account.merchant_id, + ) + .await? + .map(|profile| vec![profile]) + .get_required_value("BusinessProfile") + .change_context(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id })? } else { db.list_business_profile_by_merchant_id(&merchant_account.merchant_id) .await @@ -711,3 +721,118 @@ pub async fn retrieve_linked_routing_config( Ok(service_api::ApplicationResponse::Json(response)) } } + +pub async fn retrieve_default_routing_config_for_profiles( + state: AppState, + merchant_account: domain::MerchantAccount, +) -> RouterResponse<Vec<routing_types::ProfileDefaultRoutingConfig>> { + let db = state.store.as_ref(); + + let all_profiles = db + .list_business_profile_by_merchant_id(&merchant_account.merchant_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound) + .attach_printable("error retrieving all business profiles for merchant")?; + + let retrieve_config_futures = all_profiles + .iter() + .map(|prof| helpers::get_merchant_default_config(db, &prof.profile_id)) + .collect::<Vec<_>>(); + + let configs = futures::future::join_all(retrieve_config_futures) + .await + .into_iter() + .collect::<Result<Vec<_>, _>>()?; + + let default_configs = configs + .into_iter() + .zip(all_profiles.iter().map(|prof| prof.profile_id.clone())) + .map( + |(config, profile_id)| routing_types::ProfileDefaultRoutingConfig { + profile_id, + connectors: config, + }, + ) + .collect::<Vec<_>>(); + + Ok(service_api::ApplicationResponse::Json(default_configs)) +} + +pub async fn update_default_routing_config_for_profile( + state: AppState, + merchant_account: domain::MerchantAccount, + updated_config: Vec<routing_types::RoutableConnectorChoice>, + profile_id: String, +) -> RouterResponse<routing_types::ProfileDefaultRoutingConfig> { + let db = state.store.as_ref(); + + let business_profile = core_utils::validate_and_get_business_profile( + db, + Some(&profile_id), + &merchant_account.merchant_id, + ) + .await? + .get_required_value("BusinessProfile") + .change_context(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id })?; + let default_config = + helpers::get_merchant_default_config(db, &business_profile.profile_id).await?; + + utils::when(default_config.len() != updated_config.len(), || { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "current config and updated config have different lengths".to_string(), + }) + .into_report() + })?; + + let existing_set = FxHashSet::from_iter(default_config.iter().map(|c| { + ( + c.connector.to_string(), + #[cfg(feature = "connector_choice_mca_id")] + c.merchant_connector_id.as_ref(), + #[cfg(not(feature = "connector_choice_mca_id"))] + c.sub_label.as_ref(), + ) + })); + + let updated_set = FxHashSet::from_iter(updated_config.iter().map(|c| { + ( + c.connector.to_string(), + #[cfg(feature = "connector_choice_mca_id")] + c.merchant_connector_id.as_ref(), + #[cfg(not(feature = "connector_choice_mca_id"))] + c.sub_label.as_ref(), + ) + })); + + let symmetric_diff = existing_set + .symmetric_difference(&updated_set) + .cloned() + .collect::<Vec<_>>(); + + utils::when(!symmetric_diff.is_empty(), || { + let error_str = symmetric_diff + .into_iter() + .map(|(connector, ident)| format!("'{connector}:{ident:?}'")) + .collect::<Vec<_>>() + .join(", "); + + Err(errors::ApiErrorResponse::InvalidRequestData { + message: format!("connector mismatch between old and new configs ({error_str})"), + }) + .into_report() + })?; + + helpers::update_merchant_default_config( + db, + &business_profile.profile_id, + updated_config.clone(), + ) + .await?; + + Ok(service_api::ApplicationResponse::Json( + routing_types::ProfileDefaultRoutingConfig { + profile_id: business_profile.profile_id, + connectors: updated_config, + }, + )) +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index c34c542d1b6..7f5c720be60 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -324,6 +324,16 @@ impl Routing { web::resource("/{algorithm_id}/activate") .route(web::post().to(cloud_routing::routing_link_config)), ) + .service( + web::resource("/default/profile/{profile_id}").route( + web::post().to(cloud_routing::routing_update_default_config_for_profile), + ), + ) + .service( + web::resource("/default/profile").route( + web::get().to(cloud_routing::routing_retrieve_default_config_for_profiles), + ), + ) } } diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index b87116f47fc..606111a8881 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -296,3 +296,60 @@ pub async fn routing_retrieve_linked_config( .await } } + +#[cfg(feature = "olap")] +#[instrument(skip_all)] +pub async fn routing_retrieve_default_config_for_profiles( + state: web::Data<AppState>, + req: HttpRequest, +) -> impl Responder { + oss_api::server_wrap( + Flow::RoutingRetrieveDefaultConfig, + state, + &req, + (), + |state, auth: auth::AuthenticationData, _| { + routing::retrieve_default_routing_config_for_profiles(state, auth.merchant_account) + }, + #[cfg(not(feature = "release"))] + auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()), + #[cfg(feature = "release")] + &auth::JWTAuth, + api_locking::LockAction::NotApplicable, + ) + .await +} + +#[cfg(feature = "olap")] +#[instrument(skip_all)] +pub async fn routing_update_default_config_for_profile( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, + json_payload: web::Json<Vec<routing_types::RoutableConnectorChoice>>, +) -> impl Responder { + let routing_payload_wrapper = routing_types::RoutingPayloadWrapper { + updated_config: json_payload.into_inner(), + profile_id: path.into_inner(), + }; + oss_api::server_wrap( + Flow::RoutingUpdateDefaultConfig, + state, + &req, + routing_payload_wrapper, + |state, auth: auth::AuthenticationData, wrapper| { + routing::update_default_routing_config_for_profile( + state, + auth.merchant_account, + wrapper.updated_config, + wrapper.profile_id, + ) + }, + #[cfg(not(feature = "release"))] + auth::auth_type(&auth::ApiKeyAuth, &auth::JWTAuth, req.headers()), + #[cfg(feature = "release")] + &auth::JWTAuth, + api_locking::LockAction::NotApplicable, + ) + .await +}
2023-11-08T07:55:27Z
## Description `default-fallbacks` are defined specific to profile i.e every profile will correspond to different fallbacks and while deriving the fallbacks we are doing that based on profile. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
f88eee7362be2cc3e8e8dc2bb7bfd263892ff01e
The tests will be same as this PR: https://github.com/juspay/hyperswitch-cloud/pull/2949
[ "crates/api_models/src/events/routing.rs", "crates/api_models/src/routing.rs", "crates/router/Cargo.toml", "crates/router/src/core/admin.rs", "crates/router/src/core/payments/routing.rs", "crates/router/src/core/routing.rs", "crates/router/src/routes/app.rs", "crates/router/src/routes/routing.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2790
Bug: [BUG] Newly created business profile takes the value of `routing_algorithm` from the `merchant_account.routing_algorithm` column ### Bug Description When creating a new business profile, the value of `routing_algorithm` is taken from the merchant account's `routing_algorithm` field which may contain some stale data. ### Expected Behavior The value of the `routing_algorithm` in a newly created business profile should be a default value and not taken from anywhere. ### Actual Behavior The value of `routing_algorithm` is taken from the merchant account. ### Steps To Reproduce - ### Context For The Bug - ### Environment Integ ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 6bbe9149f4d..fe99d084223 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -124,9 +124,10 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)> .unwrap_or(merchant_account.redirect_to_merchant_with_http_post), webhook_details: webhook_details.or(merchant_account.webhook_details), metadata: request.metadata, - routing_algorithm: request - .routing_algorithm - .or(merchant_account.routing_algorithm), + routing_algorithm: Some(serde_json::json!({ + "algorithm_id": null, + "timestamp": 0 + })), intent_fulfillment_time: request .intent_fulfillment_time .map(i64::from)
2023-11-06T06:36:58Z
## Description This PR updates the code to set the value of the `business_profile.routing_algorithm` column to a default value during creation of business profile in DB. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Currently, the value of the `business_profile.routing_algorithm` field is optionally taken from the request or the merchant account, but there is no case where we want the value to be anything other than the default value. #
ab3dac79b4f138cd1f60a9afc0635dcc137a4a05
Local, compiler-guided
[ "crates/router/src/types/api/admin.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2237
Bug: [FEATURE]: [Noon] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index 45792864255..3bfcbbc6169 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -114,6 +114,10 @@ impl ConnectorCommon for Noon { "noon" } + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } + fn common_get_content_type(&self) -> &'static str { "application/json" } @@ -213,7 +217,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = noon::NoonPaymentsRequest::try_from(req)?; + let router_obj = noon::NoonRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let req_obj = noon::NoonPaymentsRequest::try_from(&router_obj)?; let noon_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<noon::NoonPaymentsRequest>::encode_to_string_of_json, @@ -519,7 +529,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let req_obj = noon::NoonPaymentsActionRequest::try_from(req)?; + let router_obj = noon::NoonRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let req_obj = noon::NoonPaymentsActionRequest::try_from(&router_obj)?; let noon_req = types::RequestBody::log_and_get_request_body( &req_obj, utils::Encode::<noon::NoonPaymentsActionRequest>::encode_to_string_of_json, diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 5ff92582051..d6b46d9743d 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -175,6 +175,39 @@ pub enum NoonApiOperations { Reverse, Refund, } + +#[derive(Debug, Serialize)] +pub struct NoonRouterData<T> { + pub amount: String, + pub router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for NoonRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (currency_unit, currency, amount, router_data): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = conn_utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data, + }) + } +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct NoonPaymentsRequest { @@ -186,10 +219,16 @@ pub struct NoonPaymentsRequest { billing: Option<NoonBilling>, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { +impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let (payment_data, currency, category) = match item.request.connector_mandate_id() { + fn try_from( + item: &NoonRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let (payment_data, currency, category) = match item + .router_data + .request + .connector_mandate_id() + { Some(subscription_identifier) => ( NoonPaymentData::Subscription(NoonSubscription { subscription_identifier, @@ -198,7 +237,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { None, ), _ => ( - match item.request.payment_method_data.clone() { + match item.router_data.request.payment_method_data.clone() { api::PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard { name_on_card: req_card.card_holder_name.clone(), number_plain: req_card.card_number.clone(), @@ -242,7 +281,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { } api_models::payments::WalletData::PaypalRedirect(_) => { Ok(NoonPaymentData::PayPal(NoonPayPal { - return_url: item.request.get_router_return_url()?, + return_url: item.router_data.request.get_router_return_url()?, })) } api_models::payments::WalletData::AliPayQr(_) @@ -291,13 +330,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { }) } }?, - Some(item.request.currency), - item.request.order_category.clone(), + Some(item.router_data.request.currency), + item.router_data.request.order_category.clone(), ), }; // The description should not have leading or trailing whitespaces, also it should not have double whitespaces and a max 50 chars according to Noon's Docs let name: String = item + .router_data .get_description()? .trim() .replace(" ", " ") @@ -305,11 +345,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { .take(50) .collect(); - let ip_address = item.request.get_ip_address_as_optional(); + let ip_address = item.router_data.request.get_ip_address_as_optional(); let channel = NoonChannels::Web; let billing = item + .router_data .address .billing .clone() @@ -326,27 +367,34 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { }, }); - let (subscription, tokenize_c_c) = - match item.request.setup_future_usage.is_some().then_some(( + let (subscription, tokenize_c_c) = match item + .router_data + .request + .setup_future_usage + .is_some() + .then_some(( NoonSubscriptionData { subscription_type: NoonSubscriptionType::Unscheduled, name: name.clone(), }, true, )) { - Some((a, b)) => (Some(a), Some(b)), - None => (None, None), - }; + Some((a, b)) => (Some(a), Some(b)), + None => (None, None), + }; let order = NoonOrder { - amount: conn_utils::to_currency_base_unit(item.request.amount, item.request.currency)?, + amount: conn_utils::to_currency_base_unit( + item.router_data.request.amount, + item.router_data.request.currency, + )?, currency, channel, category, - reference: item.connector_request_reference_id.clone(), + reference: item.router_data.connector_request_reference_id.clone(), name, ip_address, }; - let payment_action = if item.request.is_auto_capture()? { + let payment_action = if item.router_data.request.is_auto_capture()? { NoonPaymentActions::Sale } else { NoonPaymentActions::Authorize @@ -357,7 +405,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest { billing, configuration: NoonConfiguration { payment_action, - return_url: item.request.router_return_url.clone(), + return_url: item.router_data.request.router_return_url.clone(), tokenize_c_c, }, payment_data, @@ -598,19 +646,19 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NoonPaymentsCancelRequest { } } -impl<F> TryFrom<&types::RefundsRouterData<F>> for NoonPaymentsActionRequest { +impl<F> TryFrom<&NoonRouterData<&types::RefundsRouterData<F>>> for NoonPaymentsActionRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &NoonRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { let order = NoonActionOrder { - id: item.request.connector_transaction_id.clone(), + id: item.router_data.request.connector_transaction_id.clone(), }; let transaction = NoonActionTransaction { amount: conn_utils::to_currency_base_unit( - item.request.refund_amount, - item.request.currency, + item.router_data.request.refund_amount, + item.router_data.request.currency, )?, - currency: item.request.currency, - transaction_reference: Some(item.request.refund_id.clone()), + currency: item.router_data.request.currency, + transaction_reference: Some(item.router_data.request.refund_id.clone()), }; Ok(Self { api_operation: NoonApiOperations::Refund,
2023-11-05T11:34:36Z
## Description - Addressing Issue #2237 - Modified two files in `hyperswitch/crates/router/src/connector/` - `noon.rs` - Implement `get_currency_unit` function - Modify `ConnectorIntegration` implementations for `Noon` - `noon/transformers.rs` - Implement `NoonRouterData<T>` structure and functionality - Modify implementation for `NoonPaymentsRequest` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
8e484ddab8d3f4463299c7f7e8ce75b8dd628599
[ "crates/router/src/connector/noon.rs", "crates/router/src/connector/noon/transformers.rs" ]
juspay/hyperswitch
juspay__hyperswitch-2198
Bug: [FEATURE]: [ACI] Currency Unit Conversion ### :memo: Feature Description - Each currency can be described in terms of base or minor units. - For instance, when dealing with USD currency, the Cent is considered as the minor unit, while the Dollar is considered the base unit. - In Hyperswitch, the amount value is expected to be always provided in minor units. - For example: In USD, If the amount is 1 in base unit (Dollar), then it will be equivalent to 100 in minor units (Cent) - Some of the connectors integrated require the amount to be converted to a desirable unit before being passed to them. - We have functions `to_currency_base_unit` and `to_currency_lower_unit` in place to convert the minor unit amount to its decimal equivalent and vice versa. These conversions are handled explicitly based on the connector. ### :hammer: Possible Implementation - ConnectorCommon trait have been implemented for the connector. - This trait contains `get_currency_unit` method. This method needs to be implemented. - It will define what type of conversion needs to be done during `connector_router_data` creation. Concurrently handle the creation of `connector_router_data` to be passed for the connector request body creation. - You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/2196 :bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index 0a6e0d8a609..0e325a04ddb 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -30,7 +30,9 @@ impl ConnectorCommon for Aci { fn id(&self) -> &'static str { "aci" } - + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + } fn common_get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } @@ -279,7 +281,13 @@ impl req: &types::PaymentsAuthorizeRouterData, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { // encode only for for urlencoded things. - let connector_req = aci::AciPaymentsRequest::try_from(req)?; + let connector_router_data = aci::AciRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.amount, + req, + ))?; + let connector_req = aci::AciPaymentsRequest::try_from(&connector_router_data)?; let aci_req = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<aci::AciPaymentsRequest>::url_encode, @@ -471,7 +479,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref &self, req: &types::RefundsRouterData<api::Execute>, ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { - let connector_req = aci::AciRefundRequest::try_from(req)?; + let connector_router_data = aci::AciRouterData::try_from(( + &self.get_currency_unit(), + req.request.currency, + req.request.refund_amount, + req, + ))?; + let connector_req = aci::AciRefundRequest::try_from(&connector_router_data)?; let body = types::RequestBody::log_and_get_request_body( &connector_req, utils::Encode::<aci::AciRefundRequest>::url_encode, diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index f6c1daffe4d..f56369ed31a 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -17,6 +17,38 @@ use crate::{ type Error = error_stack::Report<errors::ConnectorError>; +#[derive(Debug, Serialize)] +pub struct AciRouterData<T> { + amount: String, + router_data: T, +} + +impl<T> + TryFrom<( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + )> for AciRouterData<T> +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + (currency_unit, currency, amount, item): ( + &types::api::CurrencyUnit, + types::storage::enums::Currency, + i64, + T, + ), + ) -> Result<Self, Self::Error> { + let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + Ok(Self { + amount, + router_data: item, + }) + } +} + pub struct AciAuthType { pub api_key: Secret<String>, pub entity_id: Secret<String>, @@ -101,14 +133,14 @@ impl TryFrom<&api_models::payments::WalletData> for PaymentDetails { impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::BankRedirectData, )> for PaymentDetails { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::BankRedirectData, ), ) -> Result<Self, Self::Error> { @@ -202,9 +234,9 @@ impl bank_account_bic: None, bank_account_iban: None, billing_country: Some(country.to_owned()), - merchant_customer_id: Some(Secret::new(item.get_customer_id()?)), + merchant_customer_id: Some(Secret::new(item.router_data.get_customer_id()?)), merchant_transaction_id: Some(Secret::new( - item.connector_request_reference_id.clone(), + item.router_data.connector_request_reference_id.clone(), )), customer_email: None, })) @@ -348,10 +380,12 @@ pub enum AciPaymentType { Refund, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { +impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data.clone() { + fn try_from( + item: &AciRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { api::PaymentMethodData::Card(ref card_data) => Self::try_from((item, card_data)), api::PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)), api::PaymentMethodData::PayLater(ref pay_later_data) => { @@ -361,7 +395,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { Self::try_from((item, bank_redirect_data)) } api::PaymentMethodData::MandatePayment => { - let mandate_id = item.request.mandate_id.clone().ok_or( + let mandate_id = item.router_data.request.mandate_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "mandate_id", }, @@ -376,7 +410,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { | api::PaymentMethodData::CardRedirect(_) | api::PaymentMethodData::Upi(_) | api::PaymentMethodData::Voucher(_) => Err(errors::ConnectorError::NotSupported { - message: format!("{:?}", item.payment_method), + message: format!("{:?}", item.router_data.payment_method), connector: "Aci", })?, } @@ -385,14 +419,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for AciPaymentsRequest { impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::WalletData, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::WalletData, ), ) -> Result<Self, Self::Error> { @@ -404,21 +438,21 @@ impl txn_details, payment_method, instruction: None, - shopper_result_url: item.request.router_return_url.clone(), + shopper_result_url: item.router_data.request.router_return_url.clone(), }) } } impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::BankRedirectData, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::BankRedirectData, ), ) -> Result<Self, Self::Error> { @@ -430,21 +464,21 @@ impl txn_details, payment_method, instruction: None, - shopper_result_url: item.request.router_return_url.clone(), + shopper_result_url: item.router_data.request.router_return_url.clone(), }) } } impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::PayLaterData, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, &api_models::payments::PayLaterData, ), ) -> Result<Self, Self::Error> { @@ -456,15 +490,23 @@ impl txn_details, payment_method, instruction: None, - shopper_result_url: item.request.router_return_url.clone(), + shopper_result_url: item.router_data.request.router_return_url.clone(), }) } } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AciPaymentsRequest { +impl + TryFrom<( + &AciRouterData<&types::PaymentsAuthorizeRouterData>, + &api::Card, + )> for AciPaymentsRequest +{ type Error = Error; fn try_from( - value: (&types::PaymentsAuthorizeRouterData, &api::Card), + value: ( + &AciRouterData<&types::PaymentsAuthorizeRouterData>, + &api::Card, + ), ) -> Result<Self, Self::Error> { let (item, card_data) = value; let txn_details = get_transaction_details(item)?; @@ -482,14 +524,14 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, &api::Card)> for AciPaymentsR impl TryFrom<( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, api_models::payments::MandateIds, )> for AciPaymentsRequest { type Error = Error; fn try_from( value: ( - &types::PaymentsAuthorizeRouterData, + &AciRouterData<&types::PaymentsAuthorizeRouterData>, api_models::payments::MandateIds, ), ) -> Result<Self, Self::Error> { @@ -501,32 +543,34 @@ impl txn_details, payment_method: PaymentDetails::Mandate, instruction, - shopper_result_url: item.request.router_return_url.clone(), + shopper_result_url: item.router_data.request.router_return_url.clone(), }) } } fn get_transaction_details( - item: &types::PaymentsAuthorizeRouterData, + item: &AciRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> { - let auth = AciAuthType::try_from(&item.connector_auth_type)?; + let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(TransactionDetails { entity_id: auth.entity_id, - amount: utils::to_currency_base_unit(item.request.amount, item.request.currency)?, - currency: item.request.currency.to_string(), + amount: item.amount.to_owned(), + currency: item.router_data.request.currency.to_string(), payment_type: AciPaymentType::Debit, }) } -fn get_instruction_details(item: &types::PaymentsAuthorizeRouterData) -> Option<Instruction> { - if item.request.setup_mandate_details.is_some() { +fn get_instruction_details( + item: &AciRouterData<&types::PaymentsAuthorizeRouterData>, +) -> Option<Instruction> { + if item.router_data.request.setup_mandate_details.is_some() { return Some(Instruction { mode: InstructionMode::Initial, transaction_type: InstructionType::Unscheduled, source: InstructionSource::CardholderInitiatedTransaction, create_registration: Some(true), }); - } else if item.request.mandate_id.is_some() { + } else if item.router_data.request.mandate_id.is_some() { return Some(Instruction { mode: InstructionMode::Repeated, transaction_type: InstructionType::Unscheduled, @@ -703,14 +747,13 @@ pub struct AciRefundRequest { pub entity_id: Secret<String>, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for AciRefundRequest { +impl<F> TryFrom<&AciRouterData<&types::RefundsRouterData<F>>> for AciRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { - let amount = - utils::to_currency_base_unit(item.request.refund_amount, item.request.currency)?; - let currency = item.request.currency; + fn try_from(item: &AciRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { + let amount = item.amount.to_owned(); + let currency = item.router_data.request.currency; let payment_type = AciPaymentType::Refund; - let auth = AciAuthType::try_from(&item.connector_auth_type)?; + let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?; Ok(Self { amount,
2023-10-31T17:15:03Z
## Description <!-- Describe your changes in detail --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #
42261a5306bb99d3e20eb3aa734a895e589b1d94
[ "crates/router/src/connector/aci.rs", "crates/router/src/connector/aci/transformers.rs" ]